foldkit-remote-server 0.16.0 → 0.18.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/README.md +15 -4
- package/dist/fetch.d.mts +0 -2
- package/dist/fetch.d.mts.map +1 -1
- package/dist/fetch.mjs +2 -3
- package/dist/index.d.mts +45 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/port.d.mts +0 -2
- package/dist/port.d.mts.map +1 -1
- package/dist/port.mjs +1 -2
- package/dist/{src-n8siUL2f.mjs → src-yDMwdGiL.mjs} +21 -10
- package/dist/src-yDMwdGiL.mjs.map +1 -0
- package/package.json +3 -3
- package/dist/src-n8siUL2f.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -488,10 +488,18 @@ writer that does not is refused where it is served, rather than written whatever
|
|
|
488
488
|
the row holds. A write's increments reach the writer apart from its values
|
|
489
489
|
(`increments`, each field's amount, encoded), to be added in the statement that
|
|
490
490
|
writes; a writer says it adds them (`increments: true`), and a write with one
|
|
491
|
-
over a writer that does not is refused where it is served
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
491
|
+
over a writer that does not is refused where it is served; so are computed
|
|
492
|
+
assignments (`assignments`, each a `Computation`), over a writer that computes
|
|
493
|
+
them (`assignments: true`). An increment or a computed assignment that expects
|
|
494
|
+
no revision is served only over a writer with a ledger (`ledger: true`), which
|
|
495
|
+
records each update under its `operation` and answers a retry from the record
|
|
496
|
+
(`recorded`), and only for a request carrying an operation id. Even so, a
|
|
497
|
+
concurrent pair must land as one result: an increment only of an integer, and a
|
|
498
|
+
computed assignment only where the writer `commutes` it, unless the writer pins
|
|
499
|
+
the row it read (`pins: true`, a guard with a revision). A writer
|
|
500
|
+
may refuse a write for what only its store knows (`refuses`, asked once where
|
|
501
|
+
the write is served): the Drizzle writer refuses an amount that may be a
|
|
502
|
+
fraction for a column that holds integers. An update of no row fails; an insert of an id
|
|
495
503
|
already holding what it writes answers that row, and a delete of a row already
|
|
496
504
|
gone succeeds, so a retry of either is safe. An insert of an id holding
|
|
497
505
|
anything else fails: that row is not its answer. The writer must be for the write's own Entity,
|
|
@@ -774,6 +782,9 @@ Source is responsible for any additional bounds appropriate to its backend.
|
|
|
774
782
|
real server uses, so a client sees what production would send: only the
|
|
775
783
|
fields asked for, and nested relations resolved in one read. Use it for a
|
|
776
784
|
first run, a test, a story or a demo, when there is no database yet.
|
|
785
|
+
A body calling a primitive operator runs by the `operators` it is given
|
|
786
|
+
(`Operators.kernel` by default), and one calling an operator that table lacks
|
|
787
|
+
is refused where the server is built.
|
|
777
788
|
|
|
778
789
|
```ts
|
|
779
790
|
const backend = RemoteServer.memory({
|
package/dist/fetch.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { LiveHub, ServerDefinition } from "./index.mjs";
|
|
2
2
|
import { Duration, Effect, Layer } from "effect";
|
|
3
3
|
import { RemoteUnauthenticated } from "foldkit-remote";
|
|
4
|
-
//#region src/fetch.d.ts
|
|
5
4
|
/** What `serveFetch` needs of the host runtime, per request. */
|
|
6
5
|
export interface FetchConfig<P, R, Env, RP = never> {
|
|
7
6
|
/** The server definition, as `RemoteServer.make` built it. */
|
|
@@ -73,5 +72,4 @@ export interface FetchConfig<P, R, Env, RP = never> {
|
|
|
73
72
|
* ```
|
|
74
73
|
*/
|
|
75
74
|
export declare const serveFetch: <P, R, Env, RP = never>(config: FetchConfig<P, R, Env, RP>) => ((request: Request, env: Env) => Promise<Response>);
|
|
76
|
-
//#endregion
|
|
77
75
|
//# sourceMappingURL=fetch.d.mts.map
|
package/dist/fetch.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBAqCiB,YAAY,GAAG,GAAG,KAAK;;WAE7B,QAAQ,iBAAiB,GAAG;;;;;;WAM5B,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;WAMpC,QAAQ,KAAK,QAAQ,MAAM,MAAM,IAAI;;WAErC;;;;;;;WAOA,YAAY,WAAW,MAAM,SAAS;;WAEtC,OAAO,QAAQ,GAAG;;;;;;;;;;;;WAYlB;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,gBAAgB,SAAS;;WAEzB;;WAEA;;;;;;;;;;;;;;;;;;;;;;;qBA+IE,aAAc,GAAG,GAAG,KAAK,YAAU,QACtC,YAAY,GAAG,GAAG,KAAK,UAC5B,SAAS,SAAS,KAAK,QAAQ,QAAQ"}
|
package/dist/fetch.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { r as RemoteServer, u as unauthenticatedAnswer } from "./src-
|
|
1
|
+
import { r as RemoteServer, u as unauthenticatedAnswer } from "./src-yDMwdGiL.mjs";
|
|
2
2
|
import { Cause, Deferred, Duration, Effect, Exit, Layer, Option, Schedule, Schema, Scope, Stream } from "effect";
|
|
3
3
|
import { LiveRequirement, RemoteLiveError } from "foldkit-remote";
|
|
4
|
-
|
|
4
|
+
// src/fetch.ts
|
|
5
5
|
/**
|
|
6
6
|
* `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for
|
|
7
7
|
* Cloudflare Workers and any other runtime that speaks `Request`/`Response`.
|
|
@@ -160,7 +160,6 @@ const serveFetch = (config) => {
|
|
|
160
160
|
}
|
|
161
161
|
};
|
|
162
162
|
};
|
|
163
|
-
//#endregion
|
|
164
163
|
export { serveFetch };
|
|
165
164
|
|
|
166
165
|
//# sourceMappingURL=fetch.mjs.map
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Context, Effect, Layer, Option, Schema, Stream } from "effect";
|
|
2
|
-
import { AnyQuery, AnyWrite, EntityRef, QueryEvaluateError, Row, assertSupported, evaluate, supported } from "foldkit-entity";
|
|
2
|
+
import { AnyQuery, AnyWrite, Computation, EntityRef, MemoryOperators, QueryEvaluateError, Row, WriteAssignment, assertSupported, evaluate, supported } from "foldkit-entity";
|
|
3
3
|
import { Boundary, ConnectionChangeSchema, ConnectionIdentity, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RelationRequirement, RemoteClient, RemoteDescriptor, RemoteForbidden, RemoteJsonAnswer, RemoteReadError, RemoteRpcClient, RemoteUnauthenticated, Requirement } from "foldkit-remote";
|
|
4
|
-
//#region src/index.d.ts
|
|
5
4
|
declare const RemoteServerError_base: Schema.Class<RemoteServerError, Schema.TaggedStruct<"RemoteServerError", {
|
|
6
5
|
readonly message: Schema.String;
|
|
7
6
|
}>, import("effect/Cause").YieldableError>;
|
|
@@ -114,6 +113,33 @@ export interface EntityWriter<P, R = never> {
|
|
|
114
113
|
* without it, which would leave the fields where they were.
|
|
115
114
|
*/
|
|
116
115
|
readonly increments?: true;
|
|
116
|
+
/**
|
|
117
|
+
* Whether `update` computes `assignments` where it writes, over the row it
|
|
118
|
+
* writes. `RemoteServer.write` refuses a write computing a field over a
|
|
119
|
+
* writer without it.
|
|
120
|
+
*/
|
|
121
|
+
readonly assignments?: true;
|
|
122
|
+
/**
|
|
123
|
+
* The memory table this writer works out the row a write leaves by
|
|
124
|
+
* (`Write.apply`'s), where its own statement computes it: what a wrapping
|
|
125
|
+
* writer (a guard) judges by, so it judges the value the database writes.
|
|
126
|
+
*/
|
|
127
|
+
readonly operators?: MemoryOperators | undefined;
|
|
128
|
+
/**
|
|
129
|
+
* Whether `update` writes only the row it read, at the revision it read it,
|
|
130
|
+
* whatever the write `expect`s: what a guard does so its rules judge the row
|
|
131
|
+
* written. Concurrent writes then cannot interleave, so an increment of a
|
|
132
|
+
* real number, or any computed assignment, needs no `expect` of its own.
|
|
133
|
+
*/
|
|
134
|
+
readonly pins?: true;
|
|
135
|
+
/**
|
|
136
|
+
* Whether `assignment`, landed without `expect`, gives one result whatever
|
|
137
|
+
* order concurrent writes land in: its operator `op(field, amount)`, with
|
|
138
|
+
* commutativity and associativity tested for the implementations this
|
|
139
|
+
* writer runs. `RemoteServer.write` asks of each computed assignment a
|
|
140
|
+
* write lands without a revision.
|
|
141
|
+
*/
|
|
142
|
+
readonly commutes?: (assignment: WriteAssignment) => boolean;
|
|
117
143
|
/**
|
|
118
144
|
* Whether `update` records each write it lands under its `operation`, in
|
|
119
145
|
* the transaction that writes, and answers a retry of it from that record
|
|
@@ -128,6 +154,12 @@ export interface EntityWriter<P, R = never> {
|
|
|
128
154
|
* a writer without it.
|
|
129
155
|
*/
|
|
130
156
|
readonly invariants?: true;
|
|
157
|
+
/**
|
|
158
|
+
* Why this writer cannot land `write`, each a sentence; none when it can.
|
|
159
|
+
* `RemoteServer.write` asks once, where the write is registered, for what
|
|
160
|
+
* only the store knows: a column's type, say, which the Entity does not say.
|
|
161
|
+
*/
|
|
162
|
+
readonly refuses?: (write: AnyWrite) => ReadonlyArray<string>;
|
|
131
163
|
/**
|
|
132
164
|
* The answer recorded for `operation`, when this writer has a ledger and
|
|
133
165
|
* holds one: what a wrapping writer (a guard) answers a retry with, without
|
|
@@ -149,6 +181,11 @@ export interface EntityWriter<P, R = never> {
|
|
|
149
181
|
* the statement that writes, never computed from a value read before it.
|
|
150
182
|
*/
|
|
151
183
|
readonly increments: Readonly<Record<string, number>>;
|
|
184
|
+
/**
|
|
185
|
+
* Each field to compute, as data (`Write.bind`'s): run in the statement
|
|
186
|
+
* that writes, over the row as it is there.
|
|
187
|
+
*/
|
|
188
|
+
readonly assignments: Readonly<Record<string, Computation>>;
|
|
152
189
|
/** Each `one` relation it points, by the relation's key: the row, or none. */
|
|
153
190
|
readonly links: Readonly<Record<string, Option.Option<EntityRef>>>;
|
|
154
191
|
readonly expect: Option.Option<{
|
|
@@ -405,6 +442,12 @@ export interface MemoryBackend<P = undefined> extends MemoryServed<P> {
|
|
|
405
442
|
export type MemoryConfig<P> = {
|
|
406
443
|
readonly domain: Pick<RemoteDescriptor, 'registry'>;
|
|
407
444
|
readonly rows: MemoryRows;
|
|
445
|
+
/**
|
|
446
|
+
* How the bodies' primitive operators are run: every query body is checked
|
|
447
|
+
* against it where the server is built, and one calling an operator it lacks
|
|
448
|
+
* is refused there. `Operators.kernel` when not given.
|
|
449
|
+
*/
|
|
450
|
+
readonly operators?: MemoryOperators | undefined;
|
|
408
451
|
/**
|
|
409
452
|
* Sources for entities the domain does not declare, which no row backs (a
|
|
410
453
|
* `Me` row answered from the principal, `GuardServer.me`), served beside
|
|
@@ -623,6 +666,5 @@ export declare const RemoteServer: {
|
|
|
623
666
|
*/
|
|
624
667
|
handlers: <P, R, I = never>(server: ServerDefinition<P, R>, principal: P | Context.Key<I, P>, options?: HandlerOptions<P, R>) => RemoteRpcClient<R | I>;
|
|
625
668
|
};
|
|
626
|
-
//#endregion
|
|
627
669
|
export { QueryEvaluateError, type Row, assertSupported, evaluate, supported };
|
|
628
670
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;qBAyEa,0BAA0B;;;;;;;;;qBAY1B,oBAAoB;;;;;;;;;;;;qBAUpB,sBAAsB;;iBAOlB;WACN,MAAM;WACN,OAAO,SAAS;;;;;;;;;;;;;;qBAQd,wBAAwB;iBAQpB;WACN;WACA,QAAQ,SAAS;;iBAGX,oBAAoB;WAC1B;WACA;;WAEA,UAAU,SAAS,eAAe;WAClC,WAAW;;iBAGL,aAAa,GAAG;WACtB;;WAEA,SAAS;WACT,OACP,SAAS,oBAAoB,OAC1B,OAAO,OAAO,cAAc,eAAe,mBAAmB;;WAE1D,aAAa,WAAW,GAAG;;;;;;WAM3B,UACP,WAAW,GACX,8BACG,OAAO,OAAO,UAAU,mBAAmB;;;;;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V,SAAS;eACP;eACA;eACA,QAAQ;;KAGrB,iBACA;;;;;;;;;;;EAgJO,SAAA,GAAC,UACE,gBAAgB,IAAE,kBAE3B,OAAO;aACG;aAAoD,MAAM;YAErE;;;;;;;;EA2DS,WAAA,GAAG,GAAG,WAAS,QAChB,iBAAiB,GAAG,IAAE,WACnB,IAAI,QAAQ,IAAI,GAAG,IAAE,UACvB,eAAe,GAAG,OAC1B,gBAAgB,IAAI"}
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as MutationRefused, o as QueryEvaluateError, n as RemoteInvalid, r as RemoteServer, i as RemoteServerError, a as RemoteUnmet, s as assertSupported, c as evaluate, l as supported } from "./src-
|
|
1
|
+
export { t as MutationRefused, o as QueryEvaluateError, n as RemoteInvalid, r as RemoteServer, i as RemoteServerError, a as RemoteUnmet, s as assertSupported, c as evaluate, l as supported } from "./src-yDMwdGiL.mjs";
|
package/dist/port.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Effect, Scope } from "effect";
|
|
2
2
|
import { RemoteRpcClient } from "foldkit-remote";
|
|
3
3
|
import { WorkerError } from "effect/workers/WorkerError";
|
|
4
|
-
//#region src/port.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Serves `handlers` (`RemoteServer.handlers(...)`) over `port`, returning once
|
|
7
6
|
* the client closes its end; interrupt it to stop sooner. Provide what the
|
|
@@ -9,5 +8,4 @@ import { WorkerError } from "effect/workers/WorkerError";
|
|
|
9
8
|
* breaks.
|
|
10
9
|
*/
|
|
11
10
|
export declare const servePort: <R>(handlers: RemoteRpcClient<R>, port: MessagePort) => Effect.Effect<void, WorkerError, Exclude<R, Scope.Scope>>;
|
|
12
|
-
//#endregion
|
|
13
11
|
//# sourceMappingURL=port.d.mts.map
|
package/dist/port.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"port.d.mts","names":[],"sources":["../src/port.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"port.d.mts","names":[],"sources":["../src/port.ts"],"mappings":";;;;;;;;;qBAkBa,YAAa,GAAC,UACf,gBAAgB,IAAE,MACtB,gBACL,OAAO,aAAa,aAAa,QAAQ,GAAG,MAAM"}
|
package/dist/port.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { RemoteRpc } from "foldkit-remote";
|
|
|
3
3
|
import { RpcServer } from "effect/rpc";
|
|
4
4
|
import * as WorkerRunner from "effect/workers/WorkerRunner";
|
|
5
5
|
import { portRunner } from "foldkit-remote/port";
|
|
6
|
-
|
|
6
|
+
// src/port.ts
|
|
7
7
|
/**
|
|
8
8
|
* `foldkit-remote-server/port`: `RemoteServer`'s handlers answering over a
|
|
9
9
|
* `MessagePort`, the other end of `foldkit-remote/port`'s `port`. A host in a
|
|
@@ -19,7 +19,6 @@ const servePort = (handlers, port) => {
|
|
|
19
19
|
const { platform, closed } = portRunner(port);
|
|
20
20
|
return Effect.scoped(Layer.build(RpcServer.layer(RemoteRpc).pipe(Layer.provide(RemoteRpc.toLayer(handlers)), Layer.provide(RpcServer.layerProtocolWorkerRunner), Layer.provide(Layer.succeed(WorkerRunner.WorkerRunnerPlatform)(platform)))).pipe(Effect.andThen(closed)));
|
|
21
21
|
};
|
|
22
|
-
//#endregion
|
|
23
22
|
export { servePort };
|
|
24
23
|
|
|
25
24
|
//# sourceMappingURL=port.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Context, Effect, Match, Option, Queue, Schema, Stream } from "effect";
|
|
2
|
-
import { Entity, QueryEvaluateError, Write, assertSupported, evaluate, evaluate as evaluate$1, supported } from "foldkit-entity";
|
|
2
|
+
import { Entity, Operators, QueryEvaluateError, SchemaShape, Write, assertSupported, assertSupported as assertSupported$1, evaluate, evaluate as evaluate$1, supported } from "foldkit-entity";
|
|
3
3
|
import { MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Remote, RemoteForbidden, RemoteJsonRequest, RemoteLiveError, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, RemoteUnauthenticated, Requirement, aliasedField, connectionIdentity, entityKey, refParts, refsIn, relationShape, stableStringify } from "foldkit-remote";
|
|
4
|
-
|
|
4
|
+
// src/refusal.ts
|
|
5
5
|
/** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */
|
|
6
6
|
const unauthenticatedAnswer = (refusal) => ({
|
|
7
7
|
status: 401,
|
|
@@ -10,8 +10,7 @@ const unauthenticatedAnswer = (refusal) => ({
|
|
|
10
10
|
unauthenticated: refusal.reason === void 0 ? {} : { reason: refusal.reason }
|
|
11
11
|
}
|
|
12
12
|
});
|
|
13
|
-
|
|
14
|
-
//#region src/index.ts
|
|
13
|
+
// src/index.ts
|
|
15
14
|
/**
|
|
16
15
|
* `foldkit-remote-server` — server-side Sources and handler compilation.
|
|
17
16
|
*
|
|
@@ -412,6 +411,8 @@ const pageOf = (items, window, idOf, locate) => {
|
|
|
412
411
|
};
|
|
413
412
|
};
|
|
414
413
|
function memory(config) {
|
|
414
|
+
const operators = config.operators ?? Operators.kernel;
|
|
415
|
+
for (const query of config.domain.registry.queries.values()) if (query.body !== void 0) assertSupported(query.body, operators);
|
|
415
416
|
const declared = config.domain.registry.entities;
|
|
416
417
|
const extra = /* @__PURE__ */ new Set();
|
|
417
418
|
for (const source of config.entities ?? []) {
|
|
@@ -528,7 +529,7 @@ function memory(config) {
|
|
|
528
529
|
const encoded = Schema.encodeSync(query.Input)(input);
|
|
529
530
|
const entity = body.entity.name;
|
|
530
531
|
const rows = store.rows(entity).filter((row) => readable(entity, row));
|
|
531
|
-
const matched = evaluate(body, encoded, rows);
|
|
532
|
+
const matched = evaluate(body, encoded, rows, { operators });
|
|
532
533
|
const locate = (cursor) => {
|
|
533
534
|
const row = rows.find((candidate) => String(candidate.id) === cursor);
|
|
534
535
|
if (row === void 0) throw new Error(`Cursor "${cursor}" names a row that no longer exists`);
|
|
@@ -536,7 +537,7 @@ function memory(config) {
|
|
|
536
537
|
index: evaluate({
|
|
537
538
|
...body,
|
|
538
539
|
where: []
|
|
539
|
-
}, encoded, [...matched, row]).indexOf(row),
|
|
540
|
+
}, encoded, [...matched, row], { operators }).indexOf(row),
|
|
540
541
|
exact: false
|
|
541
542
|
};
|
|
542
543
|
};
|
|
@@ -694,6 +695,16 @@ const RemoteServer = {
|
|
|
694
695
|
if (write.input.entity.name !== writer.entity) throw new Error(`[foldkit-remote-server] write "${mutation.name}" writes ${write.input.entity.name}, but its writer is for ${writer.entity}`);
|
|
695
696
|
if (write.increments.length > 0 && write.expect === void 0 && writer.ledger !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" increments a field and expects no revision, so a retry could add twice; give it \`expect\`, or a writer with a ledger`);
|
|
696
697
|
if (write.increments.length > 0 && writer.increments !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" increments a field, but its writer for ${writer.entity} does not add one (increments)`);
|
|
698
|
+
const real = write.increments.find((increment) => !SchemaShape.holdsIntegers(Schema.toEncoded(increment.field.schema).ast));
|
|
699
|
+
if (real !== void 0 && write.expect === void 0 && writer.pins !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" increments "${real.field.key}", a real number, and expects no revision; adding reals does not associate, so concurrent increments could land as two different sums. Give it \`expect\``);
|
|
700
|
+
if (write.assignments.length > 0 && writer.assignments !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" computes a field, but its writer for ${writer.entity} does not compute one (assignments)`);
|
|
701
|
+
if (write.assignments.length > 0 && write.expect === void 0) {
|
|
702
|
+
if (writer.ledger !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" computes a field and expects no revision, so a retry could compute twice; give it \`expect\`, or a writer with a ledger`);
|
|
703
|
+
const order = write.assignments.find((assignment) => writer.pins !== true && writer.commutes?.(assignment) !== true);
|
|
704
|
+
if (order !== void 0) throw new Error(`[foldkit-remote-server] write "${mutation.name}" computes "${order.field.key}" and expects no revision, but its writer does not show concurrent writes of it land as one result (its operator commuting and associating, tested); give it \`expect\``);
|
|
705
|
+
}
|
|
706
|
+
const refused = writer.refuses?.(write) ?? [];
|
|
707
|
+
if (refused.length > 0) throw new Error(`[foldkit-remote-server] write "${mutation.name}" cannot land through its writer for ${writer.entity}: ${refused.join("; ")}`);
|
|
697
708
|
const judged = Entity.invariants(write.input.entity).filter((held) => write._tag === "Update" || !Entity.readsBefore(held));
|
|
698
709
|
if (judged.length > 0 && writer.invariants !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" writes ${writer.entity}, which has invariants, but its writer does not judge them (invariants)`);
|
|
699
710
|
if (write._tag === "Insert") {
|
|
@@ -763,12 +774,13 @@ const RemoteServer = {
|
|
|
763
774
|
return Match.value(write).pipe(Match.tagsExhaustive({
|
|
764
775
|
Update: () => Effect.gen(function* () {
|
|
765
776
|
const bound = Write.bind(write, given, keys);
|
|
766
|
-
if (write.increments.length > 0 && write.expect === void 0 && Option.isNone(operation)) return yield* new RemoteServerError({ message: `${mutation.name}
|
|
777
|
+
if (write.increments.length + write.assignments.length > 0 && write.expect === void 0 && Option.isNone(operation)) return yield* new RemoteServerError({ message: `${mutation.name} moves a field with no revision, so it needs an operation id` });
|
|
767
778
|
const written = yield* invalid(unmet(bound, writer.update({
|
|
768
779
|
id: bound.id,
|
|
769
780
|
operation,
|
|
770
781
|
values: bound.values,
|
|
771
782
|
increments: bound.increments,
|
|
783
|
+
assignments: bound.assignments,
|
|
772
784
|
links: bound.links,
|
|
773
785
|
expect,
|
|
774
786
|
when: yield* when,
|
|
@@ -1123,7 +1135,6 @@ const RemoteServer = {
|
|
|
1123
1135
|
};
|
|
1124
1136
|
}
|
|
1125
1137
|
};
|
|
1126
|
-
|
|
1127
|
-
export { RemoteUnmet as a, evaluate$1 as c, RemoteServerError as i, supported as l, RemoteInvalid as n, QueryEvaluateError as o, RemoteServer as r, assertSupported as s, MutationRefused as t, unauthenticatedAnswer as u };
|
|
1138
|
+
export { RemoteUnmet as a, evaluate$1 as c, RemoteServerError as i, supported as l, RemoteInvalid as n, QueryEvaluateError as o, RemoteServer as r, assertSupported$1 as s, MutationRefused as t, unauthenticatedAnswer as u };
|
|
1128
1139
|
|
|
1129
|
-
//# sourceMappingURL=src-
|
|
1140
|
+
//# sourceMappingURL=src-yDMwdGiL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-yDMwdGiL.mjs","names":[],"sources":["../src/refusal.ts","../src/index.ts"],"sourcesContent":["import type { RemoteJsonAnswer, RemoteUnauthenticated } from 'foldkit-remote'\n\n/** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */\nexport const unauthenticatedAnswer = (refusal: RemoteUnauthenticated) =>\n ({\n status: 401,\n body: {\n error: refusal.message,\n unauthenticated: refusal.reason === undefined ? {} : { reason: refusal.reason },\n } satisfies RemoteJsonAnswer,\n }) as const\n","/**\n * `foldkit-remote-server` — server-side Sources and handler compilation.\n *\n * Owns entity/query Sources, **selection authorization**, normalization, and\n * turning them into Effect RPC handlers. It does not own HTTP, serialization, or\n * auth protocol; `principal` is resolved outside, and passed in or provided.\n */\nimport { Context, Effect, Layer, Match, Option, Queue, Schema, Stream } from 'effect'\nimport {\n Entity,\n Operators,\n SchemaShape,\n Write,\n assertSupported,\n evaluate,\n type AnyQuery,\n type MemoryOperators,\n type AnyWrite,\n type BoundWrite,\n type Computation,\n type EntityRef,\n type Row,\n type WriteAssignment,\n} from 'foldkit-entity'\nimport {\n REMOTE_PROTOCOL_VERSION,\n Remote,\n RemoteClient,\n RemoteForbidden,\n RemoteUnauthenticated,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n connectionIdentity,\n entityKey,\n refParts,\n refsIn,\n relationShape,\n stableStringify,\n type Boundary,\n type ConnectionChangeSchema,\n type ConnectionIdentity,\n type LiveChange,\n type MutationDescriptor,\n type NormalizedPatch,\n type QueryDescriptor,\n type QueryWindow,\n type RelationRequirement,\n type RemoteDescriptor,\n Requirement,\n type RemoteRpcClient,\n MutationRequest,\n QueryRequest,\n ReadBatch,\n RemoteJsonAnswer,\n RemoteJsonRequest,\n RELATION_ALIAS,\n aliasedField,\n} from 'foldkit-remote'\nimport { unauthenticatedAnswer } from './refusal.js'\n\n/** What a call `RemoteServer.answer` makes can fail with, before the answer says so. */\ntype AnswerError =\n | Schema.SchemaError\n | RemoteUnauthenticated\n | RemoteReadError\n | RemoteQueryError\n | RemoteMutationError\n | RemoteForbidden\n | RemoteProtocolError\n\nexport class RemoteServerError extends Schema.TaggedError<RemoteServerError>()(\n 'RemoteServerError',\n {\n message: Schema.String,\n },\n) {}\n\n/**\n * A writer's word that the row does not hold what the write's `when` asks of\n * it, where the write would commit: `RemoteServer.write` answers it as the\n * mutation's `Unmet` refusal.\n */\nexport class RemoteUnmet extends Schema.TaggedError<RemoteUnmet>()('RemoteUnmet', {\n message: Schema.String,\n}) {}\n\n/**\n * A writer's word that the row a write would leave breaks one of its Entity's\n * invariants: `RemoteServer.write` answers it as the mutation's `Invalid`\n * refusal. `rule` and `path` are none and empty when saying them would tell\n * the caller what a member hidden from them holds.\n */\nexport class RemoteInvalid extends Schema.TaggedError<RemoteInvalid>()('RemoteInvalid', {\n message: Schema.String,\n rule: Schema.Option(Schema.String),\n path: Schema.Array(Schema.String),\n}) {}\n\n/** A write's precondition as a writer is handed it: the body, and the input encoded. */\nexport interface WriteWhen {\n readonly body: AnyQuery\n readonly input: Readonly<Record<string, unknown>>\n}\n\n/**\n * A mutation Source's refusal, as the value its descriptor's `Refusal`\n * declares: made with `RemoteServer.refuse`, which checks the value's type\n * against the mutation, and sent to the client encoded, beside a message.\n */\nexport class MutationRefused extends Schema.TaggedError<MutationRefused>()('MutationRefused', {\n /** The mutation the refusal was made for: a Source refusing as another is a bug. */\n mutation: Schema.String,\n refusal: Schema.Unknown,\n /** What a person reads: the error's message beside the refusal. */\n message: Schema.String,\n}) {}\n\nexport interface EntityRecord {\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n}\n\nexport interface EntitySourceContext<P> {\n readonly ids: readonly string[]\n readonly fields: readonly string[]\n /** A pagination window per requested relation field. */\n readonly windows?: Readonly<Record<string, QueryWindow>> | undefined\n readonly principal: P\n}\n\nexport interface EntitySource<P, R = never> {\n readonly entity: string\n /** The fields the entity declares; a request for any other never reaches `read`. */\n readonly fields?: ReadonlySet<string> | undefined\n readonly read: (\n context: EntitySourceContext<P>,\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>\n /** Returns the fields this principal may read; omitted means all requested. */\n readonly authorize?: (principal: P, fields: readonly string[]) => readonly string[]\n /**\n * Decides, per record, what a principal sees of the fields `authorize`\n * allowed: run once per read, before `read`. A member it drops from a\n * record is settled unread, as one the source did not return.\n */\n readonly filter?: (\n principal: P,\n fields: readonly string[],\n ) => Effect.Effect<ReadPlan, RemoteServerError, R>\n /**\n * The rule that decides which rows this source returns, as it was given one\n * (a Drizzle binding's `visible`, `RemoteServer.memory`'s `readable`). The\n * server never runs it: it is here so a check at startup, such as\n * `GuardServer.validate`, can confirm a source applies the rule its Entity\n * requires.\n */\n readonly visible?: unknown\n /**\n * The fields every principal reads alike, of every row: no rule about who\n * is asking hides the row or the field, or changes its value. A promise the\n * server keeps by trusting it: the live hub sends a declared write's value\n * of one to every subscriber as it is, with no read per principal.\n */\n readonly shared?: ReadonlySet<string> | undefined\n}\n\n/** What `EntitySource.filter` decides for one read. */\nexport interface ReadPlan {\n /** The fields to read: those allowed, and any the decision itself needs. */\n readonly fields: readonly string[]\n /** One record as the principal sees it: a member dropped, or its value replaced. */\n readonly apply: (record: EntityRecord) => EntityRecord\n}\n\n/** `source.read` of `fields`, through the source's `filter` when it has one. */\nconst readFiltered = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: readonly string[],\n read: (\n fields: readonly string[],\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>,\n): Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R> =>\n source.filter === undefined\n ? read(fields)\n : Effect.flatMap(source.filter(principal, fields), plan =>\n Effect.map(read(plan.fields), records => records.map(plan.apply)),\n )\n\n/**\n * Where a declared write lands: one row's new values, encoded as the store holds\n * them. With `expect`, the row is written only while its revision is still that\n * value, and the revision moves on with the write. With `when`, only while the\n * row holds its body, checked in the statement that writes it; a row there at\n * the expected revision that does not hold it fails with `RemoteUnmet`. The row\n * as written answers; none when no row matched.\n */\nexport interface EntityWriter<P, R = never> {\n readonly entity: string\n /**\n * Whether `update` and `delete` honour `when`. `RemoteServer.write` refuses\n * a write with a precondition over a writer without it, which would write\n * whatever the row held.\n */\n readonly preconditions?: true\n /**\n * Whether `update` adds `increments` to their fields where it writes.\n * `RemoteServer.write` refuses a write with an increment over a writer\n * without it, which would leave the fields where they were.\n */\n readonly increments?: true\n /**\n * Whether `update` computes `assignments` where it writes, over the row it\n * writes. `RemoteServer.write` refuses a write computing a field over a\n * writer without it.\n */\n readonly assignments?: true\n /**\n * The memory table this writer works out the row a write leaves by\n * (`Write.apply`'s), where its own statement computes it: what a wrapping\n * writer (a guard) judges by, so it judges the value the database writes.\n */\n readonly operators?: MemoryOperators | undefined\n /**\n * Whether `update` writes only the row it read, at the revision it read it,\n * whatever the write `expect`s: what a guard does so its rules judge the row\n * written. Concurrent writes then cannot interleave, so an increment of a\n * real number, or any computed assignment, needs no `expect` of its own.\n */\n readonly pins?: true\n /**\n * Whether `assignment`, landed without `expect`, gives one result whatever\n * order concurrent writes land in: its operator `op(field, amount)`, with\n * commutativity and associativity tested for the implementations this\n * writer runs. `RemoteServer.write` asks of each computed assignment a\n * write lands without a revision.\n */\n readonly commutes?: (assignment: WriteAssignment) => boolean\n /**\n * Whether `update` records each write it lands under its `operation`, in\n * the transaction that writes, and answers a retry of it from that record\n * rather than writing again. An increment that expects no revision needs one.\n */\n readonly ledger?: true\n /**\n * Whether `update` and `insert` refuse a row, or a change, that would break\n * one of its Entity's invariants (`Entity.invariant`), with `RemoteInvalid`,\n * judged over the rows they write; an insert judges the state invariants\n * alone. `RemoteServer.write` refuses a write the Entity holds to any through\n * a writer without it.\n */\n readonly invariants?: true\n /**\n * Why this writer cannot land `write`, each a sentence; none when it can.\n * `RemoteServer.write` asks once, where the write is registered, for what\n * only the store knows: a column's type, say, which the Entity does not say.\n */\n readonly refuses?: (write: AnyWrite) => ReadonlyArray<string>\n /**\n * The answer recorded for `operation`, when this writer has a ledger and\n * holds one: what a wrapping writer (a guard) answers a retry with, without\n * deciding again over a row that has moved since.\n */\n readonly recorded?: (context: {\n readonly operation: string\n /** The row the operation writes: one operation may write several rows. */\n readonly id: string\n readonly principal: P\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n readonly update: (context: {\n readonly id: string\n /** The operation's identity across clients, when the client sent one: a ledger's key. */\n readonly operation: Option.Option<string>\n readonly values: Readonly<Record<string, unknown>>\n /**\n * Each field to move, by the amount, encoded: added to the stored value in\n * the statement that writes, never computed from a value read before it.\n */\n readonly increments: Readonly<Record<string, number>>\n /**\n * Each field to compute, as data (`Write.bind`'s): run in the statement\n * that writes, over the row as it is there.\n */\n readonly assignments: Readonly<Record<string, Computation>>\n /** Each `one` relation it points, by the relation's key: the row, or none. */\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n readonly expect: Option.Option<{ readonly field: string; readonly revision: unknown }>\n readonly when: Option.Option<WriteWhen>\n readonly principal: P\n }) => Effect.Effect<\n Option.Option<Readonly<Record<string, unknown>>>,\n RemoteServerError | RemoteForbidden | RemoteUnmet | RemoteInvalid,\n R\n >\n /**\n * Inserts the row, or finds one already there under that id holding what\n * it writes (a retry); answers the row as it is. Fails when the id holds\n * any other row.\n */\n readonly insert: (context: {\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n readonly principal: P\n }) => Effect.Effect<\n Readonly<Record<string, unknown>>,\n RemoteServerError | RemoteForbidden | RemoteInvalid,\n R\n >\n /**\n * Deletes the row, while it is still at the revision when one is expected:\n * `deleted`, `absent` (no row, so nothing to delete; a retry's case), or\n * `moved` (the row is there at another revision, and stays).\n */\n readonly delete: (context: {\n readonly id: string\n readonly expect: Option.Option<{ readonly field: string; readonly revision: unknown }>\n readonly when: Option.Option<WriteWhen>\n readonly principal: P\n }) => Effect.Effect<\n 'deleted' | 'absent' | 'moved',\n RemoteServerError | RemoteForbidden | RemoteUnmet,\n R\n >\n /**\n * The row as `principal` may see it, under the read rule its Source applies:\n * none when there is no such row, or it is hidden. Given, a write's answer\n * is read back through it, so an answer never shows its writer a row it may\n * not read, and a row the write hid from them answers as deleted.\n */\n readonly read?: (context: {\n readonly id: string\n readonly fields: ReadonlyArray<string>\n readonly principal: P\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n /**\n * Each of `relations`' links as stored, by ref key (`'Project:p1'`) or\n * `null`, whatever a reader may see of the row it points at; none when there\n * is no such row. A guard reads it to tell a write that unlinks a row hidden\n * from its writer from one that changes nothing.\n */\n readonly linked?: (context: {\n readonly id: string\n readonly relations: ReadonlyArray<string>\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n}\n\n/** A connection change a mutation made, as the wire carries it. */\nexport type ConnectionChange = Schema.Schema.Type<typeof ConnectionChangeSchema>\n\nconst connectionChange = (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n position: 'prepend' | 'append' | 'remove',\n): ConnectionChange => {\n const edge = { entity: ref.entity, id: ref.id, key: entityKey(ref.entity, ref.id) }\n return position === 'remove'\n ? { _tag: 'Remove', connection: connectionIdentity(connection), edge }\n : { _tag: 'Insert', connection: connectionIdentity(connection), position, edge }\n}\n\n/**\n * The requested fields, in request order, that the source declares and the\n * principal may read. Never a field the client did not request, even if a\n * permissive `authorize` returns more.\n */\nconst allowedFields = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n requested: ReadonlyArray<string>,\n): ReadonlyArray<string> => {\n const declared =\n source.fields === undefined ? requested : requested.filter(field => source.fields!.has(field))\n if (declared.length === 0) return []\n const permitted = new Set(\n source.authorize === undefined ? declared : source.authorize(principal, declared),\n )\n return declared.filter(field => permitted.has(field))\n}\n\n/** The windows of the fields being read; only a field being read carries its window. */\nconst windowsOf = (\n windows: Readonly<Record<string, QueryWindow>> | undefined,\n fields: ReadonlyArray<string>,\n): { readonly windows?: Readonly<Record<string, QueryWindow>> } => {\n if (windows === undefined) return {}\n const kept = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(windows, field) ? [[field, windows[field]!] as const] : [],\n ),\n )\n return Object.keys(kept).length === 0 ? {} : { windows: kept }\n}\n\nexport interface MutationOutcome<Output> {\n readonly output: Output\n readonly entities?: ReadonlyArray<NormalizedPatch>\n /** Connection changes the mutation made; the client settles them with its patches. */\n readonly connections?: ReadonlyArray<ConnectionChange>\n /**\n * Entities the mutation deleted. The client knows them absent from then on:\n * they leave every connection and read `NotFound`, with no connection to name.\n */\n readonly deleted?: ReadonlyArray<{ readonly entity: string; readonly id: string }>\n}\n\nexport interface MutationSource<P, R = never> {\n readonly mutation: string\n /**\n * For a declared write (`RemoteServer.write`), the Entity it writes, the\n * writer it lands through, as it was given one, and the write itself. The\n * server never reads it; a startup check such as `GuardServer.validate` does.\n */\n readonly writes?: { readonly entity: string; readonly writer: unknown; readonly write: AnyWrite }\n readonly Input: Schema.Codec<unknown>\n readonly Output: Schema.Codec<unknown>\n readonly Refusal: Schema.Codec<unknown, unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly principal: P\n /**\n * The client's id for this request, the same on every retry of it. It is\n * unique within that client only: two clients' first requests can share\n * it. Key a record of the write by `operation`, never by this.\n */\n readonly requestId: string\n /**\n * The operation's identity across clients, the same on every retry of it,\n * when the client sent one (Remote's does); none from an older client.\n */\n readonly operation: Option.Option<string>\n /** For a declared write: the input keys to write, when the client named only some. */\n readonly keys?: ReadonlyArray<string> | undefined\n }) => Effect.Effect<\n {\n readonly output: unknown\n readonly entities: ReadonlyArray<NormalizedPatch>\n readonly connections: ReadonlyArray<ConnectionChange>\n readonly deleted: ReadonlyArray<{ readonly entity: string; readonly id: string }>\n },\n RemoteServerError | MutationRefused | RemoteForbidden,\n R\n >\n}\n\nexport interface QueryPage {\n readonly edges: ReadonlyArray<{\n readonly entity: string\n readonly id: string\n readonly key: string\n }>\n readonly start: Boundary\n readonly end: Boundary\n}\n\nexport interface QuerySource<P, R = never> {\n readonly query: string\n readonly Input: Schema.Codec<unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly window: QueryWindow\n readonly principal: P\n /**\n * What the client reads of each item. A source may use it to answer\n * fields with the page, or ignore it: the handlers fetch what the page\n * leaves out through the entity sources, so one response still carries\n * both either way.\n */\n readonly select?: RelationRequirement | undefined\n }) => Effect.Effect<QueryPage, RemoteServerError, R>\n /** The rule that decides which rows the query lists. See `EntitySource.visible`. */\n readonly visible?: unknown\n}\n\nexport interface LiveSource<P, R = never> {\n readonly entity: string\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n }) => Stream.Stream<Schema.Schema.Type<typeof LiveChange>, RemoteServerError, R>\n}\n\nexport interface ServerDefinition<P, R = never> {\n readonly entities: ReadonlyMap<string, EntitySource<P, R>>\n readonly mutations: ReadonlyMap<string, MutationSource<P, R>>\n readonly queries: ReadonlyMap<string, QuerySource<P, R>>\n readonly live: ReadonlyMap<string, LiveSource<P, R>>\n}\n\n/** A read batch may not carry more than this many distinct ids per entity. */\nconst DEFAULT_MAX_IDS_PER_ENTITY = 1000\n\n/** A nested selection may not reach further than this many relation levels. */\nconst DEFAULT_MAX_DEPTH = 8\n\nexport interface HandlerOptions<P, R = never> {\n /** A read or live subscription may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many relation levels; default 8. */\n readonly maxDepth?: number | undefined\n /** A hub whose `changed`/`deleted` signals reach the subscribers this handler registers. */\n readonly live?: LiveHub<P, R> | undefined\n}\n\n/** Fails when the requirements name more distinct ids of one entity than `maxIds`. */\n/**\n * Each page of a relation read beside another is a source read of its own, and\n * the names come from the client, so how many one relation may have is bounded.\n * A screen shows a list and a page or two of it, not dozens.\n */\nconst MAX_PAGES_PER_RELATION = 4\n\n/** The relation a request pages more ways than allowed, at any depth; `undefined` when none. */\nconst checkPagesPerRelation = (\n requirements: ReadonlyArray<RelationRequirement>,\n): string | undefined => {\n for (const requirement of requirements) {\n const pages = new Map<string, number>()\n for (const name of requirement.fields) {\n if (!name.includes(RELATION_ALIAS)) continue\n const field = aliasedField(name)\n const count = (pages.get(field) ?? 0) + 1\n if (count > MAX_PAGES_PER_RELATION) return `${requirement.entity}.${field}`\n pages.set(field, count)\n }\n const nested = checkPagesPerRelation(Object.values(requirement.relations ?? {}))\n if (nested !== undefined) return nested\n }\n return undefined\n}\n\nconst checkIdsPerEntity = (\n requirements: ReadonlyArray<Requirement>,\n maxIds: number,\n): string | undefined => {\n const ids = new Map<string, Set<string>>()\n for (const requirement of requirements) {\n const seen = ids.get(requirement.entity) ?? new Set<string>()\n seen.add(requirement.id)\n ids.set(requirement.entity, seen)\n if (seen.size > maxIds) return requirement.entity\n }\n return undefined\n}\n\ntype LiveChangeValue = Schema.Schema.Type<typeof LiveChange>\ntype Uncursored<T> = T extends unknown ? Omit<T, 'cursor'> : never\n\ninterface LiveRef {\n readonly entity: string\n readonly id: string\n}\n\n/**\n * The server-side \"these fields changed\" signal. A hub tracks each live\n * subscriber's requirements (entity, id, fields) and principal; `changed`\n * re-reads the changed fields a subscriber selects through the entity's own\n * source, under that subscriber's principal, and streams the patch to it.\n * Subscribers that select none of the changed fields do no work. Cursors\n * continue from the cursor each subscriber resumed at, so the client's\n * duplicate and gap handling is unchanged.\n */\nexport interface LiveHub<P, R = never> {\n /**\n * `values`, when given, are the row's stored values of `fields` (a declared\n * write's answer): a field of them the source declares `shared` is sent as\n * it is, and only the rest are re-read.\n */\n readonly changed: (\n ref: LiveRef,\n fields: ReadonlyArray<string>,\n values?: Readonly<Record<string, unknown>> | undefined,\n ) => Effect.Effect<void, RemoteServerError, R>\n /**\n * `ref` may be gone: each subscriber's selection of it is read again, and\n * one it is no longer there to is sent a deletion. A row deleted for one\n * writer may only be hidden from them, and still there to others.\n */\n readonly deleted: (ref: LiveRef) => Effect.Effect<void, RemoteServerError, R>\n /** Registers a subscriber for the stream's lifetime; `handlers` calls this. */\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n /** Refuses a subscription naming more ids of one entity than this. */\n readonly maxIdsPerEntity?: number | undefined\n }) => Stream.Stream<LiveChangeValue, RemoteServerError>\n /** How many subscribers are registered now. */\n readonly size: Effect.Effect<number>\n}\n\ninterface Selected {\n readonly fields: Set<string>\n /** The window each paged field was subscribed with, so a re-read pages the same way. */\n readonly windows: Map<string, QueryWindow>\n}\n\n/** The subscribers one source read answers, and the fields each wants of it. */\ninterface ReadGroup<P> {\n readonly windows: Readonly<Record<string, QueryWindow>>\n /** The alias each field read here is answered under. */\n readonly renames: Readonly<Record<string, string>>\n readonly entries: Array<{ readonly subscriber: Subscriber<P>; readonly fields: string[] }>\n}\n\ninterface Subscriber<P> {\n /** Per entity:id, the fields (and their windows) this subscriber selects. */\n readonly selected: ReadonlyMap<string, Selected>\n readonly principal: P\n readonly queue: Queue.Queue<LiveChangeValue>\n cursor: number\n}\n\nconst liveHub = <P, R>(\n entities: ReadonlyArray<EntitySource<P, R>>,\n options: {\n /**\n * Who a principal is, for sharing re-reads: subscribers whose principals\n * have one key share one read, under the first one's principal. Default:\n * the principal itself, so only the same value shares.\n */\n readonly key?: ((principal: P) => unknown) | undefined\n } = {},\n): Effect.Effect<LiveHub<P, R>> =>\n Effect.sync(() => {\n const keyOf = options.key ?? ((principal: P): unknown => principal)\n const sources = new Map(entities.map(source => [source.entity, source]))\n const subscribers = new Set<Subscriber<P>>()\n const emit = (subscriber: Subscriber<P>, change: Uncursored<LiveChangeValue>) => {\n subscriber.cursor += 1\n return Queue.offer(subscriber.queue, {\n ...change,\n cursor: subscriber.cursor,\n } as LiveChangeValue)\n }\n\n /**\n * Re-reads row `ref` for each subscriber that selects it, of `which` of\n * its fields (none: every field it selects), and sends what it now sees:\n * a patch, or, where the row is no longer there to it, a deletion. One\n * group's failed read fails the call after the others are sent.\n */\n const refresh = (\n ref: LiveRef,\n which: Option.Option<ReadonlyArray<string>>,\n values: Readonly<Record<string, unknown>> | undefined,\n ): Effect.Effect<void, RemoteServerError, R> =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n const source = sources.get(ref.entity)\n if (source === undefined) {\n // Nothing to ask: a deletion reaches every subscriber as it is.\n if (Option.isSome(which)) return\n for (const subscriber of subscribers) {\n if (subscriber.selected.has(key))\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n }\n return\n }\n // A shared field's written value is every subscriber's alike: it needs no read.\n const given = (field: string) =>\n values !== undefined &&\n source.shared !== undefined &&\n source.shared.has(field) &&\n Object.hasOwn(values, field)\n // One source read per principal key and window signature:\n // subscribers sharing both share the read, and a paged field is\n // re-read with the window the subscriber selected it with.\n const groups = new Map<\n unknown,\n { readonly principal: P; readonly byWindows: Map<string, ReadGroup<P>> }\n >()\n for (const subscriber of subscribers) {\n const selected = subscriber.selected.get(key)\n if (selected === undefined) continue\n const fields = Option.getOrElse(which, () => [\n ...new Set([...selected.fields].map(aliasedField)),\n ])\n const principalKey = keyOf(subscriber.principal)\n const sharing = groups.get(principalKey) ?? {\n principal: subscriber.principal,\n byWindows: new Map<string, ReadGroup<P>>(),\n }\n groups.set(principalKey, sharing)\n const { byWindows } = sharing\n const join = (\n windows: Readonly<Record<string, QueryWindow>>,\n renames: Readonly<Record<string, string>>,\n wanted: string[],\n ): void => {\n const groupKey = `${stableStringify(windows)}\\u0000${stableStringify(renames)}`\n const group = byWindows.get(groupKey) ?? { windows, renames, entries: [] }\n byWindows.set(groupKey, group)\n group.entries.push({ subscriber, fields: wanted })\n }\n const selects = fields.filter(field => selected.fields.has(field))\n // A paged field is read with its subscriber's window, so it is never sent as written.\n const sent = selects.filter(field => given(field) && !selected.windows.has(field))\n if (sent.length > 0) {\n const patch: Record<string, unknown> = Object.create(null)\n for (const field of sent) patch[field] = values![field]\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values: patch,\n changed: sent,\n })\n }\n const sentSet = new Set(sent)\n const wanted = selects.filter(field => !sentSet.has(field))\n if (wanted.length > 0)\n join(\n Object.fromEntries(\n wanted.flatMap(field => {\n const window = selected.windows.get(field)\n return window === undefined ? [] : [[field, window] as const]\n }),\n ),\n {},\n wanted,\n )\n // A page read under an alias changes when the relation it reads does, and\n // is re-read on its own, with its window, so the whole list can be too.\n for (const alias of selected.fields) {\n const window = selected.windows.get(alias)\n const field = aliasedField(alias)\n if (field === alias || window === undefined || !fields.includes(field)) continue\n join({ [field]: window }, { [field]: alias }, [field])\n }\n }\n const gone = new Set<Subscriber<P>>()\n const read = (\n principal: P,\n { windows, renames, entries: group }: ReadGroup<P>,\n ): Effect.Effect<void, RemoteServerError, R> =>\n Effect.gen(function* () {\n const requested = [...new Set(group.flatMap(entry => entry.fields))]\n const allowed = allowedFields(source, principal, requested)\n if (allowed.length === 0) return\n const allowedSet = new Set(allowed)\n const records = yield* readFiltered(source, principal, allowed, fields =>\n source.read({ ids: [ref.id], fields, principal, ...windowsOf(windows, allowed) }),\n )\n const record = records.find(candidate => candidate.id === ref.id)\n for (const { subscriber, fields: wanted } of group) {\n if (gone.has(subscriber)) continue\n if (record === undefined) {\n // Deleted, or no longer there to this principal: either way, gone.\n gone.add(subscriber)\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n continue\n }\n const values: Record<string, unknown> = Object.create(null)\n for (const field of wanted) {\n if (allowedSet.has(field) && Object.hasOwn(record.values, field)) {\n values[renamed(renames, field)] = record.values[field]\n }\n }\n const changed = Object.keys(values)\n if (changed.length === 0) continue\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values,\n changed,\n })\n }\n })\n const failures: Array<RemoteServerError> = []\n for (const { principal, byWindows } of groups.values()) {\n for (const group of byWindows.values()) {\n yield* read(principal, group).pipe(\n Effect.catch(error => Effect.sync(() => void failures.push(error))),\n )\n }\n }\n if (failures.length > 0) return yield* Effect.fail(failures[0]!)\n })\n\n return {\n subscribe: ({ requirements, after, principal, maxIdsPerEntity }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const over = checkIdsPerEntity(\n requirements,\n Math.max(1, maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY),\n )\n if (over !== undefined) {\n return yield* new RemoteServerError({\n message: `Too many \"${over}\" ids in one live subscription`,\n })\n }\n const paged = checkPagesPerRelation(requirements)\n if (paged !== undefined) {\n return yield* new RemoteServerError({\n message: `Too many pages of \"${paged}\" in one live subscription`,\n })\n }\n const selected = new Map<string, Selected>()\n for (const requirement of requirements) {\n const key = `${requirement.entity}:${requirement.id}`\n const entry = selected.get(key) ?? { fields: new Set<string>(), windows: new Map() }\n for (const field of requirement.fields) entry.fields.add(field)\n for (const [field, window] of Object.entries(requirement.windows ?? {})) {\n entry.windows.set(field, window)\n }\n selected.set(key, entry)\n }\n const subscriber: Subscriber<P> = {\n selected,\n principal,\n queue: yield* Queue.unbounded<LiveChangeValue>(),\n cursor: after,\n }\n subscribers.add(subscriber)\n return Stream.fromQueue(subscriber.queue).pipe(\n Stream.ensuring(Effect.sync(() => void subscribers.delete(subscriber))),\n )\n }),\n ),\n\n changed: (ref, fields, values) => refresh(ref, Option.some(fields), values),\n // Gone for one writer may be hidden from them alone: each subscriber is asked again.\n deleted: ref => refresh(ref, Option.none(), undefined),\n\n size: Effect.sync(() => subscribers.size),\n }\n })\n\nconst protocolMismatch = (received: number): RemoteProtocolError | undefined =>\n received === REMOTE_PROTOCOL_VERSION\n ? undefined\n : new RemoteProtocolError({\n message: `Remote protocol version ${received} is not ${REMOTE_PROTOCOL_VERSION}`,\n expected: REMOTE_PROTOCOL_VERSION,\n received,\n })\n\ninterface EntityGroup {\n /** The fields each id was asked for: the union is read, and one id is settled only for its own. */\n readonly ids: Map<string, Set<string>>\n /** The union of the requests' fields, windows, and relations. */\n slice: RelationRequirement\n /** The alias each field read here is answered under; see `RELATION_ALIAS`. */\n readonly renames: Readonly<Record<string, string>>\n}\n\n/** A request, or the part of one that reads a relation under an alias. */\ntype Part = Requirement & { readonly renames?: Readonly<Record<string, string>> }\n\n/**\n * The name a field is answered under. A requested field is client input, so\n * `constructor` must find no rename rather than `Object.prototype`'s.\n */\nconst renamed = (renames: Readonly<Record<string, string>>, field: string): string =>\n Object.hasOwn(renames, field) ? renames[field]! : field\n\nconst pickNames = <T>(\n record: Readonly<Record<string, T>> | undefined,\n names: ReadonlyArray<string>,\n): Readonly<Record<string, T>> | undefined => {\n if (record === undefined) return undefined\n const picked = names.flatMap(name =>\n Object.hasOwn(record, name) ? [[name, record[name]!] as const] : [],\n )\n return picked.length === 0 ? undefined : Object.fromEntries(picked)\n}\n\n/**\n * A request's aliased fields, each as a read of its own. `comments@first=10` is\n * the `comments` relation read with the alias's window, so a source sees the\n * field it knows and one window for it, while the whole list rides beside it in\n * another read. The answer goes back under the alias, which is also the key of\n * the relation followed from it.\n */\nconst splitAliases = (request: Requirement): ReadonlyArray<Part> => {\n const aliases = request.fields.filter(field => field.includes(RELATION_ALIAS))\n if (aliases.length === 0) return [request]\n const plain = request.fields.filter(field => !field.includes(RELATION_ALIAS))\n interface Building {\n fields: string[]\n windows: Record<string, QueryWindow>\n relations: Record<string, RelationRequirement>\n renames: Record<string, string>\n }\n // Keyed by requested field names, so a `__proto__` names an entry, not the prototype.\n const keyed = <T>(entries?: Readonly<Record<string, T>>): Record<string, T> =>\n Object.assign(Object.create(null) as Record<string, T>, entries)\n const first: Building = {\n fields: [...plain],\n windows: keyed(pickNames(request.windows, plain)),\n relations: keyed(pickNames(request.relations, plain)),\n renames: keyed(),\n }\n const building: Building[] = [first]\n for (const alias of aliases) {\n const window = request.windows?.[alias]\n // An alias is a page: one that names no window asks for nothing.\n if (window === undefined) continue\n const field = aliasedField(alias)\n // It rides in a read that does not already read its relation, so a request\n // costs one read unless the list and a page of it are both wanted.\n let part = building.find(candidate => !candidate.fields.includes(field))\n if (part === undefined) {\n part = { fields: [], windows: keyed(), relations: keyed(), renames: keyed() }\n building.push(part)\n }\n part.fields.push(field)\n part.windows[field] = window\n part.renames[field] = alias\n const relation = request.relations?.[alias]\n if (relation !== undefined) part.relations[alias] = relation\n }\n return building\n .filter(part => part.fields.length > 0)\n .map(part => ({\n entity: request.entity,\n id: request.id,\n fields: part.fields,\n ...(Object.keys(part.windows).length === 0 ? {} : { windows: part.windows }),\n ...(Object.keys(part.relations).length === 0 ? {} : { relations: part.relations }),\n ...(Object.keys(part.renames).length === 0 ? {} : { renames: part.renames }),\n }))\n}\n\n/**\n * One level's requests grouped per entity and window signature: ids and\n * slices unioned. Requests that page a relation differently are separate\n * groups, so one window never answers for another id.\n */\nconst groupByEntity = (requests: ReadonlyArray<Requirement>): EntityGroup[] => {\n const grouped = new Map<string, EntityGroup>()\n for (const request of requests.flatMap(splitAliases)) {\n const renames = request.renames ?? {}\n const groupKey = `${request.entity}\\u0000${stableStringify(request.windows ?? null)}\\u0000${stableStringify(renames)}`\n const group = grouped.get(groupKey)\n if (group === undefined) {\n grouped.set(groupKey, {\n ids: new Map([[request.id, new Set(request.fields)]]),\n slice: Requirement.mergeRelation({ entity: request.entity, fields: [] }, request),\n renames,\n })\n } else {\n const asked = group.ids.get(request.id) ?? new Set<string>()\n for (const field of request.fields) asked.add(field)\n group.ids.set(request.id, asked)\n group.slice = Requirement.mergeRelation(group.slice, request)\n }\n }\n return [...grouped.values()]\n}\n\n/**\n * A descriptor's name and, when it declares them, its readable members: an\n * Entity's `members` (its fields, relations and derived members), or a plain\n * descriptor's `fields`.\n */\ninterface EntityName {\n readonly name: string\n readonly fields?: Readonly<Record<string, unknown>> | undefined\n readonly members?: Readonly<Record<string, unknown>> | undefined\n}\n\n/** One entity's rows in their wire shape: a relation is its ref key, `'User:u1'`. */\nexport type MemoryRows = Readonly<\n Record<string, ReadonlyArray<Readonly<Record<string, unknown>> & { readonly id: string }>>\n>\n\n/**\n * The rows a memory backend holds, which its mutations write through. A\n * change is what the next read sees; nothing is pushed to a client.\n */\nexport interface MemoryStore {\n /** The rows of one entity, in insertion order. */\n readonly rows: (entity: string) => ReadonlyArray<Readonly<Record<string, unknown>>>\n /** Writes these values onto a row, creating it if it is new. */\n readonly write: (entity: string, id: string, values: Readonly<Record<string, unknown>>) => void\n readonly remove: (entity: string, id: string) => void\n}\n\n/**\n * A memory backend made without a `principal`: its rows and the server over\n * them, answered as whoever its caller names per request (`serveFetch`,\n * `RemoteServer.handlers(served.server, principal)`).\n */\nexport interface MemoryServed<P> extends MemoryStore {\n /**\n * The rows' server, for serving them over a real transport, or as any\n * principal: `RemoteRpc.toLayer(RemoteServer.handlers(backend.server, principal))`.\n */\n readonly server: ServerDefinition<P>\n}\n\nexport interface MemoryBackend<P = undefined> extends MemoryServed<P> {\n /**\n * A `RemoteClient` answering from the rows as the configured `principal`.\n * Provide it where the real one would go.\n */\n readonly layer: Layer.Layer<RemoteClient>\n}\n\n/** What `RemoteServer.memory` is made from. See `memory`. */\nexport type MemoryConfig<P> = {\n readonly domain: Pick<RemoteDescriptor, 'registry'>\n readonly rows: MemoryRows\n /**\n * How the bodies' primitive operators are run: every query body is checked\n * against it where the server is built, and one calling an operator it lacks\n * is refused there. `Operators.kernel` when not given.\n */\n readonly operators?: MemoryOperators | undefined\n /**\n * Sources for entities the domain does not declare, which no row backs (a\n * `Me` row answered from the principal, `GuardServer.me`), served beside\n * the rows. One for a declared entity is refused: the rows serve it.\n */\n readonly entities?: ReadonlyArray<EntitySource<P>>\n /** Sources for queries, beside the domain's: one named as a declared query answers it instead of its body. */\n readonly queries?: ReadonlyArray<QuerySource<P>>\n readonly mutations?: (store: MemoryStore) => ReadonlyArray<MutationSource<P>>\n /** Per entity name, the fields a principal may read, as `RemoteServer.entity` takes it. */\n readonly authorize?: Readonly<Record<string, NonNullable<EntitySource<P>['authorize']>>>\n /** Per entity name, what a principal sees of each record, as `RemoteServer.entity` takes it. */\n readonly filter?: Readonly<Record<string, NonNullable<EntitySource<P>['filter']>>>\n /** Per entity name, the fields every principal reads alike: see `EntitySource.shared`. */\n readonly shared?: Readonly<Record<string, ReadonlyArray<string>>>\n /**\n * Which stored rows a principal may read, decided once per read. A row it\n * may not read is absent from a read by id and from every query, and a ref\n * to one is dropped from a relation (a `one` ref reads as `null`). `row`\n * looks another stored row up, for a decision that follows a relation.\n */\n readonly readable?: (\n principal: P,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ) => Effect.Effect<MemoryReadable, RemoteServerError>\n /** Who the `layer` answers as. Without it there is no `layer`, unless `P` admits `undefined`. */\n readonly principal?: P\n}\n\n/** What a backend needs to give a `layer`: a principal to answer as, or one `undefined` can be. */\nexport type MemoryAnswering<P> = undefined extends P ? unknown : { readonly principal: P }\n\n/** Whether a stored row of `entity` may be read, given its whole stored values. */\nexport type MemoryReadable = (entity: string, row: Readonly<Record<string, unknown>>) => boolean\n\n/** Where a cursor falls among ordered items: before `index`, or at it when `exact`. */\ninterface Position {\n readonly index: number\n readonly exact: boolean\n}\n\n/**\n * One page of ordered items for a window, as a real server pages them. A\n * cursor is an item's id: a forward page starts at the `after` it was asked\n * for and ends at its last item while more follow, a backward page the\n * mirror, so a page fetched from another's end cursor joins it.\n *\n * `locate` places a cursor that is not among the items, as a keyset does: a\n * row that stopped matching still has a place in the order. Without it, such\n * a cursor is an error. A page of no items has no id of its own to end at, so\n * with more beyond it and no cursor to repeat, its boundary is `Unknown`.\n */\nconst pageOf = <Item>(\n items: ReadonlyArray<Item>,\n window: QueryWindow,\n idOf: (item: Item) => string,\n locate?: (cursor: string) => Position,\n): { readonly items: ReadonlyArray<Item>; readonly start: Boundary; readonly end: Boundary } => {\n if (\n (window.after !== undefined && window.before !== undefined) ||\n (window.first !== undefined && window.last !== undefined)\n ) {\n throw new Error('A query window cannot combine after with before, or first with last')\n }\n const position = (cursor: string): Position => {\n const index = items.findIndex(item => idOf(item) === cursor)\n if (index >= 0) return { index, exact: true }\n if (locate !== undefined) return locate(cursor)\n throw new Error(`Cursor \"${cursor}\" names nothing in these results`)\n }\n const cursor = (id: string): Boundary => ({ _tag: 'Cursor', cursor: id })\n const terminal: Boundary = { _tag: 'Terminal' }\n const unknown: Boundary = { _tag: 'Unknown' }\n if (window.last !== undefined || window.before !== undefined) {\n const to = window.before === undefined ? items.length : position(window.before).index\n const from = window.last === undefined ? 0 : Math.max(0, to - window.last)\n const page = items.slice(from, to)\n const start =\n from === 0\n ? terminal\n : page.length > 0\n ? cursor(idOf(page[0]!))\n : window.before === undefined\n ? unknown\n : cursor(window.before)\n return {\n items: page,\n start,\n end: window.before === undefined ? terminal : cursor(window.before),\n }\n }\n const at = window.after === undefined ? undefined : position(window.after)\n const from = at === undefined ? 0 : at.exact ? at.index + 1 : at.index\n const to = window.first === undefined ? items.length : Math.min(items.length, from + window.first)\n const page = items.slice(from, to)\n const end =\n to >= items.length\n ? terminal\n : page.length > 0\n ? cursor(idOf(page.at(-1)!))\n : window.after === undefined\n ? unknown\n : cursor(window.after)\n return { items: page, start: window.after === undefined ? terminal : cursor(window.after), end }\n}\n\n/**\n * A backend held in memory: the rows you give it, served through the same\n * handlers a real server uses. For a first run, a test, a story or a demo, with\n * no database and no network.\n *\n * Reads go through `handlers`, so field filtering and nested relations behave\n * as they do in production. A query declared with `Query.define` is answered\n * by running its body over the rows with the reference interpreter, the one\n * every interpreter is held to by the conformance suite. A query with no body\n * has nothing to run and is refused when the backend is made, unless `queries`\n * supplies a source for it. Mutations are yours to give: each one writes\n * through the store it is handed, and the next read sees the change.\n *\n * Every field of every row is readable unless `authorize` names the entity:\n * then its function decides, per principal, as `RemoteServer.entity`'s does.\n * `entities` adds Sources for entities no row backs, which the domain must not\n * declare. The `layer` answers as `principal`, and is absent without one\n * (unless `P` admits `undefined`); `server` answers as any. It does not push\n * live changes. It is not a server to deploy.\n */\nfunction memory<P = undefined>(config: MemoryConfig<P> & MemoryAnswering<P>): MemoryBackend<P>\nfunction memory<P = undefined>(config: MemoryConfig<P>): MemoryServed<P>\nfunction memory<P = undefined>(config: MemoryConfig<P>): MemoryBackend<P> {\n const operators = config.operators ?? Operators.kernel\n // A body this table cannot run would fail on its first read: refuse it here.\n for (const query of config.domain.registry.queries.values()) {\n if (query.body !== undefined) assertSupported(query.body, operators)\n }\n const declared = config.domain.registry.entities\n const extra = new Set<string>()\n for (const source of config.entities ?? []) {\n if (declared.has(source.entity))\n throw new Error(\n `RemoteServer.memory: \"${source.entity}\" is a declared entity, which the rows serve; give its rows, or leave it out of the domain and keep its source`,\n )\n if (extra.has(source.entity))\n throw new Error(`RemoteServer.memory: two sources in \\`entities\\` serve \"${source.entity}\"`)\n extra.add(source.entity)\n }\n const authorize = config.authorize ?? {}\n const filter = config.filter ?? {}\n const shared = config.shared ?? {}\n for (const [option, given] of [\n ['authorize', authorize],\n ['filter', filter],\n ['shared', shared],\n ] as const) {\n const unknown = Object.keys(given).filter(name => !config.domain.registry.entities.has(name))\n if (unknown.length > 0) {\n throw new Error(\n `RemoteServer.memory: \\`${option}\\` names ${unknown.map(name => `\"${name}\"`).join(', ')}, which the domain does not declare`,\n )\n }\n }\n for (const [name, fields] of Object.entries(shared)) {\n const entity: EntityName = config.domain.registry.entities.get(name)!\n const declared = entity.members ?? entity.fields\n const unserved = fields.filter(\n field => declared !== undefined && !Object.hasOwn(declared, field),\n )\n if (unserved.length > 0) {\n throw new Error(\n `RemoteServer.memory: ${name}'s shared fields name no member: ${unserved.join(', ')}`,\n )\n }\n }\n const everyRow: MemoryReadable = () => true\n const readableFor = (principal: P) =>\n config.readable === undefined\n ? Effect.succeed(everyRow)\n : config.readable(principal, (entity, id) => Option.fromUndefinedOr(table(entity).get(id)))\n const tables = new Map<string, Map<string, Record<string, unknown>>>()\n const table = (entity: string) => {\n const existing = tables.get(entity)\n if (existing !== undefined) return existing\n const created = new Map<string, Record<string, unknown>>()\n tables.set(entity, created)\n return created\n }\n for (const [entity, rows] of Object.entries(config.rows)) {\n // Keyed by the id as the wire carries it, a string, whatever JSON gave.\n for (const row of rows) table(entity).set(String(row.id), { ...row })\n }\n const store: MemoryStore = {\n rows: entity => [...table(entity).values()],\n write: (entity, id, values) => {\n table(entity).set(id, { ...table(entity).get(id), id, ...values })\n },\n remove: (entity, id) => {\n table(entity).delete(id)\n },\n }\n\n // A relation page is the refs in a window of the stored list. Its cursor is a\n // ref key, or a bare id, as a real server accepts either.\n const valueFor = (value: unknown, window: QueryWindow | undefined): unknown => {\n if (window === undefined || !Array.isArray(value)) return value\n // A ref listed twice would make a cursor ambiguous, and paging cycle.\n const refs = [...new Set(value as ReadonlyArray<string>)]\n const idOf = (ref: string) => ref.slice(ref.indexOf(':') + 1)\n const named = (cursor: string | undefined) =>\n cursor === undefined ? undefined : cursor.includes(':') ? idOf(cursor) : cursor\n let page: ReturnType<typeof pageOf<string>>\n try {\n page = pageOf(\n refs,\n { ...window, after: named(window.after), before: named(window.before) },\n idOf,\n )\n } catch {\n // A cursor that names nothing in the list answers this one field with an\n // empty page. Failing would fail the whole batch it rode in, every other\n // entity and field with it.\n return { refs: [], hasNext: false, hasPrevious: false }\n }\n // A cursor at either end is exactly \"more lie that way\".\n return {\n refs: page.items,\n hasNext: page.end._tag === 'Cursor',\n hasPrevious: page.start._tag === 'Cursor',\n }\n }\n\n // A relation's value is a ref, or a list of them; a ref to a row the\n // principal may not read is not shown, as a database binding hides it.\n const relationsOf = new Map(\n [...config.domain.registry.entities].map(([name, descriptor]) => [\n name,\n new Set(\n Object.entries(descriptor.fields as Readonly<Record<string, Schema.Top>>).flatMap(\n ([field, schema]) => (relationShape(schema) === undefined ? [] : [field]),\n ),\n ),\n ]),\n )\n const refsShown = (readable: MemoryReadable, entity: string, field: string, value: unknown) => {\n if (readable === everyRow || relationsOf.get(entity)?.has(field) !== true) return value\n const shown = (ref: unknown) => {\n if (typeof ref !== 'string') return true\n const { entity: target, id } = refParts(ref)\n const row = table(target).get(id)\n return row !== undefined && readable(target, row)\n }\n if (Array.isArray(value)) return value.filter(shown)\n return shown(value) ? value : null\n }\n\n // Every row this backend reads, it reads through `readable`.\n const visible = config.readable === undefined ? {} : { visible: config.readable }\n const entities = [...config.domain.registry.entities.keys()].map(name => ({\n ...visible,\n ...RemoteServer.entity<P>(\n { name },\n {\n ...(Object.hasOwn(authorize, name) ? { authorize: authorize[name]! } : {}),\n ...(Object.hasOwn(filter, name) ? { filter: filter[name]! } : {}),\n ...(Object.hasOwn(shared, name) ? { shared: shared[name]! } : {}),\n read: ({ ids, fields, windows, principal }) =>\n Effect.flatMap(readableFor(principal), readable =>\n Effect.try({\n try: () =>\n ids.flatMap(id => {\n const row = table(name).get(id)\n if (row === undefined || !readable(name, row)) return []\n const values = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(row, field)\n ? [\n [\n field,\n valueFor(\n refsShown(readable, name, field, row[field]),\n windows?.[field],\n ),\n ] as const,\n ]\n : [],\n ),\n )\n return [{ id, values }]\n }),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n ),\n },\n ),\n }))\n\n const given = new Set((config.queries ?? []).map(source => source.query))\n const bodiless = [...config.domain.registry.queries.values()].filter(\n query => query.body === undefined && !given.has(query.name),\n )\n if (bodiless.length > 0) {\n throw new Error(\n `RemoteServer.memory: ${bodiless.map(query => `\"${query.name}\"`).join(', ')} ${bodiless.length === 1 ? 'has' : 'have'} no body to run. Declare ${bodiless.length === 1 ? 'it' : 'them'} with Query.define, or give a source in \\`queries\\`.`,\n )\n }\n const queries = [\n ...(config.queries ?? []),\n ...[...config.domain.registry.queries.values()]\n .filter(query => !given.has(query.name))\n .map(query => ({\n ...visible,\n ...RemoteServer.query<P>(query, ({ input, window, principal }) =>\n Effect.flatMap(readableFor(principal), readable =>\n Effect.try({\n try: () => {\n const body = query.body!\n const encoded = Schema.encodeSync(query.Input)(input) as Readonly<\n Record<string, unknown>\n >\n const entity = body.entity.name\n const rows = (store.rows(entity) as ReadonlyArray<Row>).filter(row =>\n readable(entity, row),\n )\n const matched = evaluate(body, encoded, rows, { operators })\n // A cursor row that no longer matches still has a place in the\n // order, as a keyset has it: sort it among the matches with the\n // predicates set aside. One that no longer exists has none.\n const locate = (cursor: string) => {\n const row = rows.find(candidate => String(candidate.id) === cursor)\n if (row === undefined) {\n throw new Error(`Cursor \"${cursor}\" names a row that no longer exists`)\n }\n const placed = evaluate(\n { ...body, where: [] } as typeof body,\n encoded,\n [...matched, row],\n { operators },\n )\n return { index: placed.indexOf(row), exact: false }\n }\n const page = pageOf(matched, window, row => String(row.id), locate)\n return {\n edges: page.items.map(row => {\n const id = String(row.id)\n return { entity, id, key: entityKey(entity, id) }\n }),\n start: page.start,\n end: page.end,\n }\n },\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n ),\n ),\n })),\n ]\n\n const server = RemoteServer.make<P>({\n entities: [...entities, ...(config.entities ?? [])],\n queries,\n mutations: config.mutations?.(store) ?? [],\n })\n return {\n ...store,\n server,\n // Typed only where `principal` was given or `P` admits `undefined` (the\n // overloads): otherwise it would answer as nobody, and is not offered.\n layer: Remote.clientLayer(\n RemoteServer.handlers(server, config.principal as P),\n ) as Layer.Layer<RemoteClient>,\n }\n}\n\n/**\n * A Source's refusal as the client receives it: encoded by the mutation's own\n * `Refusal`. A refusal made for another mutation, or one the mutation does not\n * declare, is this side's bug, and says so without the value.\n */\nconst refusalError = (\n Refusal: Schema.Codec<unknown, unknown>,\n mutation: string,\n refused: MutationRefused,\n): Effect.Effect<never, RemoteMutationError> =>\n Effect.gen(function* () {\n const invalid = new RemoteMutationError({ message: 'Invalid mutation refusal' })\n if (refused.mutation !== mutation) return yield* invalid\n const encoded = yield* Schema.encodeUnknownEffect(Refusal)(refused.refusal).pipe(\n Effect.mapError(() => invalid),\n )\n return yield* new RemoteMutationError({ message: refused.message, refusal: encoded })\n })\n\nexport const RemoteServer = {\n /** A backend held in memory, for a first run, a test or a demo. See `memory`. */\n memory,\n\n /** A mutation outcome's report that `ref` now heads the connection. */\n prepend: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'prepend'),\n\n /** A mutation outcome's report that `ref` now ends the connection. */\n append: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'append'),\n\n /** A mutation outcome's report that `ref` left the connection. */\n remove: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'remove'),\n\n /**\n * An entity source. Given the Entity, every member it declares (fields,\n * relations, derived members) may be requested; given anything with a\n * `name` and `fields`, those fields. A request for anything else never\n * reaches `read` or `authorize`. Given only a `name`, every field passes.\n */\n entity: <P = unknown, R = never>(\n entity: EntityName,\n options: {\n readonly read: EntitySource<P, R>['read']\n readonly authorize?: EntitySource<P, R>['authorize']\n readonly filter?: EntitySource<P, R>['filter']\n /** See `EntitySource.shared`: each must be a member the source serves. */\n readonly shared?: ReadonlyArray<string> | undefined\n },\n ): EntitySource<P, R> => {\n const declared = entity.members ?? entity.fields\n const fields = declared === undefined ? undefined : new Set(Object.keys(declared))\n const unserved = (options.shared ?? []).filter(\n field => fields !== undefined && !fields.has(field),\n )\n if (unserved.length > 0) {\n throw new Error(\n `[foldkit-remote-server] ${entity.name}'s shared fields name no member: ${unserved.join(', ')}`,\n )\n }\n return {\n entity: entity.name,\n ...(fields === undefined ? {} : { fields }),\n read: options.read,\n ...(options.authorize === undefined ? {} : { authorize: options.authorize }),\n ...(options.filter === undefined ? {} : { filter: options.filter }),\n ...(options.shared === undefined ? {} : { shared: new Set(options.shared) }),\n }\n },\n\n mutation: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n Refused = unknown,\n >(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n run: (context: {\n readonly input: Input\n readonly principal: P\n /** The client's id for this request, unique within that client only. */\n readonly requestId: string\n /** The operation's identity across clients, for a record of the write; see `MutationSource`. */\n readonly operation: Option.Option<string>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n R\n >,\n ): MutationSource<P, R> => ({\n mutation: mutation.name,\n Input: mutation.Input,\n Output: mutation.Output,\n Refusal: mutation.Refusal,\n run: context =>\n run({\n input: context.input as Input,\n principal: context.principal,\n requestId: context.requestId,\n operation: context.operation,\n }).pipe(\n Effect.map(outcome => ({\n output: outcome.output,\n entities: outcome.entities ?? [],\n connections: outcome.connections ?? [],\n deleted: outcome.deleted ?? [],\n })),\n ),\n }),\n\n /**\n * A refusal of `mutation`, as a value of its declared `Refusal`: fail a\n * Source with it (`yield* RemoteServer.refuse(SavePost, { _tag: 'Field', ... })`)\n * and the client reads it, decoded, with `Data.refusal`. `message` is what a\n * person reads, beside it.\n */\n refuse: <Refused>(\n mutation: MutationDescriptor<string, any, any, Refused>,\n refusal: NoInfer<Refused>,\n message = `Mutation ${mutation.name} was refused`,\n ): MutationRefused => new MutationRefused({ mutation: mutation.name, refusal, message }),\n\n /**\n * A writer's refusal of a row that does not hold the write's `when`: fail\n * `update` or `delete` with it (`yield* RemoteServer.unmet()`), and\n * `RemoteServer.write` answers the mutation's `Unmet` refusal.\n */\n unmet: (message = 'The row does not hold what the write asks of it'): RemoteUnmet =>\n new RemoteUnmet({ message }),\n\n /**\n * A writer's refusal of a row that would break an invariant: fail `update`\n * or `insert` with it, naming the invariant's id and path when the caller\n * may be told them, and `RemoteServer.write` answers the mutation's\n * `Invalid` refusal.\n */\n invalid: (\n message: string,\n rule: Option.Option<string> = Option.none(),\n path: ReadonlyArray<string> = [],\n ): RemoteInvalid => new RemoteInvalid({ message, rule, path }),\n\n /**\n * A refusal of who is asking: fail a Source with it\n * (`yield* RemoteServer.forbid()`) and the write never runs. `reason`, when\n * given, is what the person who asked reads; without it the refusal says\n * nothing of why. `answer` sends it as a 403, and the client's mutation\n * fails with `_tag: 'Forbidden'`.\n */\n forbid: (reason?: string): RemoteForbidden =>\n new RemoteForbidden({\n message: reason ?? 'Forbidden',\n ...(reason === undefined ? {} : { reason }),\n }),\n\n /**\n * A refusal of a caller who could not be told: a `serveFetch` or\n * `defineDocumentHost` resolver fails with it (`RemoteServer.unauthenticated()`)\n * when the credential it was sent no longer holds. It answers 401, with\n * `reason`, when given, for the person who asked.\n */\n unauthenticated: (reason?: string): RemoteUnauthenticated =>\n new RemoteUnauthenticated({\n message: reason ?? 'Unauthenticated',\n ...(reason === undefined ? {} : { reason }),\n }),\n\n /**\n * The Source of a mutation that is a declared `Write`, with no handler: the\n * input bound to the write lands through `writer`, and the row as written\n * answers as a patch (a deletion as `deleted`). An update writes only the\n * keys the client named, when it named some, and fails for a row that is not\n * there; an insert of an id already holding what it writes (a retry)\n * answers with that row, and of one holding anything else fails; a delete of\n * a row already gone succeeds. A row that moved past the revision the write\n * `expect`s is refused as a conflict, and one that does not hold its `when`\n * as unmet; a write with a `when` needs a writer that checks it\n * (`preconditions`), and is refused here without one.\n */\n write: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Refused extends { readonly _tag: 'Conflict' | 'Unmet' | 'Invalid' } = {\n readonly _tag: 'Conflict'\n },\n >(\n mutation: MutationDescriptor<Name, Input, {}, Refused> & {\n readonly write: AnyWrite\n },\n writer: EntityWriter<P, R>,\n ): MutationSource<P, R> => {\n const { write } = mutation\n if (write.input.entity.name !== writer.entity) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" writes ${write.input.entity.name}, but its writer is for ${writer.entity}`,\n )\n }\n // Without a revision, only a ledger tells a retry of an increment from a second one.\n if (write.increments.length > 0 && write.expect === undefined && writer.ledger !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" increments a field and expects no revision, so a retry could add twice; give it \\`expect\\`, or a writer with a ledger`,\n )\n }\n if (write.increments.length > 0 && writer.increments !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" increments a field, but its writer for ${writer.entity} does not add one (increments)`,\n )\n }\n // Concurrent increments land in either order: one result only where adding\n // associates, which integers do and floating-point reals do not.\n const real = write.increments.find(\n increment => !SchemaShape.holdsIntegers(Schema.toEncoded(increment.field.schema).ast),\n )\n if (real !== undefined && write.expect === undefined && writer.pins !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" increments \"${real.field.key}\", a real number, and expects no revision; adding reals does not associate, so concurrent increments could land as two different sums. Give it \\`expect\\``,\n )\n }\n if (write.assignments.length > 0 && writer.assignments !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" computes a field, but its writer for ${writer.entity} does not compute one (assignments)`,\n )\n }\n if (write.assignments.length > 0 && write.expect === undefined) {\n if (writer.ledger !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" computes a field and expects no revision, so a retry could compute twice; give it \\`expect\\`, or a writer with a ledger`,\n )\n }\n const order = write.assignments.find(\n assignment => writer.pins !== true && writer.commutes?.(assignment) !== true,\n )\n if (order !== undefined) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" computes \"${order.field.key}\" and expects no revision, but its writer does not show concurrent writes of it land as one result (its operator commuting and associating, tested); give it \\`expect\\``,\n )\n }\n }\n const refused = writer.refuses?.(write) ?? []\n if (refused.length > 0) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" cannot land through its writer for ${writer.entity}: ${refused.join('; ')}`,\n )\n }\n // An update judges every invariant; an insert, with no row before, the state ones alone.\n const judged = Entity.invariants(write.input.entity).filter(\n held => write._tag === 'Update' || !Entity.readsBefore(held),\n )\n if (judged.length > 0 && writer.invariants !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" writes ${writer.entity}, which has invariants, but its writer does not judge them (invariants)`,\n )\n }\n // An insert's row is its values: a field it leaves to a default the writer cannot judge.\n if (write._tag === 'Insert') {\n const sets = new Set(['id', ...write.sets.map(set => set.field.key)])\n const unset = judged.flatMap(held =>\n held.after.filter(key => !sets.has(key)).map(key => `${held.id} reads ${key}`),\n )\n if (unset.length > 0) {\n throw new Error(\n `[foldkit-remote-server] insert \"${mutation.name}\" leaves unset a field an invariant reads (${unset.join('; ')})`,\n )\n }\n }\n if (Option.isSome(write.when) && writer.preconditions !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" has a precondition, but its writer for ${writer.entity} does not check one (preconditions)`,\n )\n }\n const encodeInput = Schema.encodeUnknownEffect(\n write.input.schema as unknown as Schema.Codec<unknown, Readonly<Record<string, unknown>>>,\n )\n return {\n mutation: mutation.name,\n writes: { entity: writer.entity, writer, write },\n Input: mutation.Input,\n Output: mutation.Output,\n Refusal: mutation.Refusal,\n run: ({ input, principal, keys, operation }) => {\n const given = input as never\n const expect = Write.expected(write, given)\n const conflict = (bound: { readonly entity: string; readonly id: string }) =>\n RemoteServer.refuse(\n mutation,\n { _tag: 'Conflict' } as Refused,\n `${bound.entity} ${bound.id} changed since it was read`,\n )\n // The body reads the input as a query's does: encoded, by its keys.\n const when = Option.match(write.when, {\n onNone: () => Effect.succeed(Option.none<WriteWhen>()),\n onSome: body =>\n encodeInput(given).pipe(\n Effect.map(encoded => Option.some({ body, input: encoded })),\n Effect.mapError(\n () => new RemoteServerError({ message: `${mutation.name}'s input did not encode` }),\n ),\n ),\n })\n const unmet = <A>(\n bound: { readonly entity: string; readonly id: string },\n writing: Effect.Effect<\n A,\n RemoteServerError | RemoteForbidden | RemoteUnmet | RemoteInvalid,\n R\n >,\n ) =>\n Effect.catchTag(\n writing,\n 'RemoteUnmet',\n (): Effect.Effect<never, RemoteServerError | MutationRefused> =>\n Option.isNone(write.when)\n ? // A writer unmet with no precondition to meet is wrong, and the\n // mutation declares no such refusal: the server's error, not one.\n Effect.fail(\n new RemoteServerError({\n message: `${writer.entity}'s writer refused ${mutation.name}, which has no precondition, as unmet`,\n }),\n )\n : Effect.fail(\n RemoteServer.refuse(\n mutation,\n { _tag: 'Unmet' } as Refused,\n `${bound.entity} ${bound.id} does not hold what ${mutation.name} asks of it`,\n ),\n ),\n )\n // The writer judged the row it would leave; the client is told what the writer said.\n const invalid = <A>(\n writing: Effect.Effect<\n A,\n RemoteServerError | RemoteForbidden | MutationRefused | RemoteInvalid,\n R\n >,\n ) =>\n Effect.catchTag(writing, 'RemoteInvalid', refused =>\n Effect.fail(\n RemoteServer.refuse(\n mutation,\n {\n _tag: 'Invalid',\n rule: refused.rule,\n message: refused.message,\n path: refused.path,\n } as unknown as Refused,\n refused.message,\n ),\n ),\n )\n const answered = (bound: BoundWrite, values: Readonly<Record<string, unknown>>) => {\n const read = writer.read\n const shown =\n read === undefined\n ? Effect.succeed(Option.some(values))\n : read({ id: bound.id, fields: Object.keys(values), principal })\n return Effect.map(\n shown,\n Option.match({\n onNone: () => ({\n output: {},\n entities: [],\n connections: [],\n deleted: [{ entity: bound.entity, id: bound.id }],\n }),\n onSome: seen => ({\n output: {},\n entities: [{ entity: bound.entity, id: bound.id, values: seen }],\n connections: [],\n deleted: [],\n }),\n }),\n )\n }\n return Match.value(write).pipe(\n Match.tagsExhaustive({\n Update: () =>\n Effect.gen(function* () {\n const bound = Write.bind(write, given, keys)\n if (\n write.increments.length + write.assignments.length > 0 &&\n write.expect === undefined &&\n Option.isNone(operation)\n ) {\n // The ledger keys a write by its operation: with none, a retry could add twice.\n return yield* new RemoteServerError({\n message: `${mutation.name} moves a field with no revision, so it needs an operation id`,\n })\n }\n const written = yield* invalid(\n unmet(\n bound,\n writer.update({\n id: bound.id,\n operation,\n values: bound.values,\n increments: bound.increments,\n assignments: bound.assignments,\n links: bound.links,\n expect,\n when: yield* when,\n principal,\n }),\n ),\n )\n if (Option.isSome(written)) return yield* answered(bound, written.value)\n return yield* Option.isSome(expect)\n ? Effect.fail(conflict(bound))\n : Effect.fail(\n new RemoteServerError({\n message: `No ${bound.entity} ${bound.id} to update`,\n }),\n )\n }),\n // Written whole: there is no row a client could have changed some keys of.\n Insert: () =>\n Effect.gen(function* () {\n const bound = Write.bind(write, given)\n const row = yield* invalid(\n writer.insert({\n id: bound.id,\n values: bound.values,\n links: bound.links,\n principal,\n }),\n )\n return yield* answered(bound, row)\n }),\n Delete: () =>\n Effect.gen(function* () {\n const bound = Write.bind(write, given)\n const outcome = yield* invalid(\n unmet(\n bound,\n writer.delete({ id: bound.id, expect, when: yield* when, principal }),\n ),\n )\n // Gone already is gone: only a revision the row moved past refuses.\n if (outcome === 'moved') return yield* Effect.fail(conflict(bound))\n return {\n output: {},\n entities: [],\n connections: [],\n deleted: [{ entity: bound.entity, id: bound.id }],\n }\n }),\n }),\n )\n },\n }\n },\n\n query: <P = unknown, R = never, Input = unknown>(\n query: QueryDescriptor<string, Input, unknown>,\n run: (context: {\n readonly input: Input\n readonly window: QueryWindow\n readonly principal: P\n readonly select?: RelationRequirement | undefined\n }) => Effect.Effect<QueryPage, RemoteServerError, R>,\n ): QuerySource<P, R> => ({\n query: query.name,\n Input: query.Input,\n run: context =>\n run({\n input: context.input as Input,\n window: context.window,\n principal: context.principal,\n ...(context.select === undefined ? {} : { select: context.select }),\n }),\n }),\n\n /** Streams live entity patches for a client's live requirements. */\n live: <P = unknown, R = never>(\n entity: EntityName,\n options: { readonly subscribe: LiveSource<P, R>['subscribe'] },\n ): LiveSource<P, R> => ({\n entity: entity.name,\n subscribe: options.subscribe,\n }),\n\n /**\n * A `LiveHub` over entity sources. Pass it to `handlers` as `live`, and every\n * mutation's answered patches and deletions are published to it; call\n * `hub.changed(ref, fields)` yourself only for a write that is not a\n * mutation (a database trigger, a job). Each subscriber that selects any of\n * those fields receives them, re-read through the entity source under its\n * own principal.\n */\n liveHub,\n\n make: <P = unknown, R = never>(config: {\n readonly entities: readonly EntitySource<P, R>[]\n readonly mutations?: readonly MutationSource<P, R>[]\n readonly queries?: readonly QuerySource<P, R>[]\n readonly live?: readonly LiveSource<P, R>[]\n }): ServerDefinition<P, R> => ({\n entities: new Map(config.entities.map(source => [source.entity, source])),\n mutations: new Map((config.mutations ?? []).map(source => [source.mutation, source])),\n queries: new Map((config.queries ?? []).map(source => [source.query, source])),\n live: new Map((config.live ?? []).map(source => [source.entity, source])),\n }),\n\n /**\n * Checks every source name against the declared domain, so an undeclared\n * entity/query/mutation fails at startup rather than returning nothing at\n * call time.\n */\n validate: (domain: RemoteDescriptor, server: ServerDefinition<any, any>): void => {\n const assertDeclared = (\n kind: string,\n declared: ReadonlyMap<string, unknown>,\n names: Iterable<string>,\n ): void => {\n for (const name of names) {\n if (!declared.has(name))\n throw new Error(`RemoteServer: ${kind} \"${name}\" is not declared in the Remote domain`)\n }\n }\n assertDeclared('entity', domain.registry.entities, server.entities.keys())\n assertDeclared('query', domain.registry.queries, server.queries.keys())\n assertDeclared('mutation', domain.registry.mutations, server.mutations.keys())\n },\n\n /**\n * Reads entity requirements through the entity sources, level by level,\n * following relations as `FoldkitRemoteRead` does. Shared by the read\n * handler and the query handler's payload: a query page's items are just\n * requirements the page names, so one response carries both.\n */\n readHelper: <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R>,\n requests: ReadonlyArray<Requirement>,\n ): Effect.Effect<\n {\n readonly entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }>\n readonly settled: Array<{\n readonly entity: string\n readonly id: string\n readonly fields: Array<string>\n }>\n },\n RemoteReadError,\n R\n > =>\n Effect.gen(function* () {\n const entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }> = []\n const settled = new Map<string, { entity: string; id: string; fields: Set<string> }>()\n const settle = (entity: string, id: string, fields: ReadonlyArray<string>): void => {\n if (fields.length === 0) return\n const key = `${entity}:${id}`\n const entry = settled.get(key) ?? { entity, id, fields: new Set<string>() }\n for (const field of fields) entry.fields.add(field)\n settled.set(key, entry)\n }\n const fetched = new Map<string, Set<string>>()\n const fetchedValues = new Map<string, Record<string, unknown>>()\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH\n const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY)\n\n const over = checkIdsPerEntity(requests, maxIds)\n if (over !== undefined) {\n return yield* new RemoteReadError({ message: `Too many \"${over}\" ids in one read batch` })\n }\n const paged = checkPagesPerRelation(requests)\n if (paged !== undefined) {\n return yield* new RemoteReadError({ message: `Too many pages of \"${paged}\" in one read` })\n }\n\n let pending: ReadonlyArray<Requirement> = requests\n for (let depth = 0; pending.length > 0; depth++) {\n if (depth > maxDepth) {\n return yield* new RemoteReadError({\n message: `Nested selection deeper than ${maxDepth} relation levels`,\n })\n }\n const next: Requirement[] = []\n\n const follow = (\n values: Record<string, unknown>,\n relations: Readonly<Record<string, RelationRequirement>>,\n ): void => {\n for (const [field, relation] of Object.entries(relations)) {\n if (!Object.hasOwn(values, field)) continue\n for (const ref of refsIn(values[field])) {\n if (ref.entity !== relation.entity) continue\n const key = `${relation.entity}:${ref.id}`\n const read = fetched.get(key)\n const fields = relation.fields.filter(name => read?.has(name) !== true)\n if (fields.length > 0) {\n next.push({\n entity: relation.entity,\n id: ref.id,\n fields,\n ...(relation.windows === undefined ? {} : { windows: relation.windows }),\n ...(relation.relations === undefined ? {} : { relations: relation.relations }),\n })\n } else if (relation.relations !== undefined) {\n follow(fetchedValues.get(key) ?? {}, relation.relations)\n }\n }\n }\n }\n\n for (const { ids, slice, renames } of groupByEntity(pending)) {\n const name = slice.entity\n const source = server.entities.get(name)\n if (source === undefined) continue\n const allowed = allowedFields(source, principal, slice.fields)\n const allowedSet = new Set(allowed)\n const idList = [...ids.keys()]\n for (const [id, asked] of ids) {\n settle(\n name,\n id,\n [...asked]\n .filter(field => !allowedSet.has(field))\n .map(field => renamed(renames, field)),\n )\n }\n if (allowed.length === 0) continue\n\n const windows = windowsOf(slice.windows, allowed)\n const records = yield* readFiltered(source, principal, allowed, fields =>\n Effect.map(\n Effect.forEach(\n Array.from({ length: Math.ceil(idList.length / maxIds) }, (_, chunk) =>\n idList.slice(chunk * maxIds, (chunk + 1) * maxIds),\n ),\n chunk => source.read({ ids: chunk, fields, principal, ...windows }),\n ),\n chunks => chunks.flat(),\n ),\n ).pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n )\n\n for (const record of records) {\n const values: Record<string, unknown> = Object.create(null)\n const omitted: string[] = []\n const asked = ids.get(record.id)\n for (const field of allowed) {\n if (Object.hasOwn(record.values, field))\n values[renamed(renames, field)] = record.values[field]\n else if (asked?.has(field) === true) omitted.push(renamed(renames, field))\n }\n entities.push({ entity: name, id: record.id, values })\n settle(name, record.id, omitted)\n\n const key = `${name}:${record.id}`\n const known = fetched.get(key) ?? new Set<string>()\n for (const field of allowed) known.add(renamed(renames, field))\n fetched.set(key, known)\n fetchedValues.set(key, { ...fetchedValues.get(key), ...values })\n\n follow(values, slice.relations ?? {})\n }\n }\n pending = next.flatMap(request => {\n const read = fetched.get(`${request.entity}:${request.id}`)\n const fields = request.fields.filter(field => read?.has(field) !== true)\n return fields.length === 0 ? [] : [{ ...request, fields }]\n })\n }\n\n return {\n entities,\n settled: [...settled.values()].map(entry => ({ ...entry, fields: [...entry.fields] })),\n }\n }),\n\n /**\n * Answers one JSON request through `handlers`: what an HTTP endpoint, a\n * worker or a server in the page calls with the body it received, parsed.\n * The request and its payload are decoded by the protocol's own schemas\n * before a handler sees them, so an operation name is one of Remote's three\n * and nothing else. A body that is not a request is a 400; a caller who\n * could not be told a 401; a refusal of who is asking a 403; a handler's\n * failure a 500 with its message; a defect a 500 that says nothing of it.\n * `Remote.json` and `Remote.http` are the other end.\n */\n answer: <R>(\n handlers: RemoteRpcClient<R>,\n body: unknown,\n ): Effect.Effect<\n { readonly status: 200 | 400 | 401 | 403 | 422 | 500; readonly body: RemoteJsonAnswer },\n never,\n R\n > => {\n const asked = {\n read: (payload: unknown) =>\n Effect.flatMap(Schema.decodeUnknownEffect(ReadBatch)(payload), handlers.FoldkitRemoteRead),\n query: (payload: unknown) =>\n Effect.flatMap(\n Schema.decodeUnknownEffect(QueryRequest)(payload),\n handlers.FoldkitRemoteQuery,\n ),\n mutate: (payload: unknown) =>\n Effect.flatMap(\n Schema.decodeUnknownEffect(MutationRequest)(payload),\n handlers.FoldkitRemoteMutate,\n ),\n }\n return Schema.decodeUnknownEffect(RemoteJsonRequest)(body).pipe(\n Effect.flatMap(({ operation, payload }): Effect.Effect<unknown, AnswerError, R> =>\n asked[operation](payload),\n ),\n Effect.map(result => ({ status: 200 as const, body: { result } })),\n Effect.catchTag('SchemaError', error =>\n Effect.succeed({ status: 400 as const, body: { error: error.message } }),\n ),\n Effect.catchTag('Unauthenticated', error => Effect.succeed(unauthenticatedAnswer(error))),\n Effect.catchTag('Forbidden', error =>\n Effect.succeed({\n status: 403 as const,\n body: {\n error: error.message,\n forbidden: error.reason === undefined ? {} : { reason: error.reason },\n },\n }),\n ),\n // A refusal is the mutation's answer, not a failure of the server.\n Effect.catchTag('RemoteMutationError', error =>\n Effect.succeed(\n error.refusal === undefined\n ? { status: 500 as const, body: { error: error.message } }\n : { status: 422 as const, body: { error: error.message, refusal: error.refusal } },\n ),\n ),\n Effect.catch(error =>\n Effect.succeed({ status: 500 as const, body: { error: error.message } }),\n ),\n // A defect is a bug on this side: the caller learns there was one, not what.\n Effect.catchCause(() =>\n Effect.succeed({ status: 500 as const, body: { error: 'Internal error' } }),\n ),\n )\n },\n\n /**\n * Compiles the server into Remote's RPC handlers, answering as `principal`:\n * a value, or a Context key (`G.Principal`) read on each call, which\n * authentication provides per request. Unknown entities, entities with no\n * allowed fields, and unknown mutations return an error or nothing rather\n * than leaking existence.\n */\n handlers: <P, R, I = never>(\n server: ServerDefinition<P, R>,\n principal: P | Context.Key<I, P>,\n options: HandlerOptions<P, R> = {},\n ): RemoteRpcClient<R | I> => {\n // A Context key is read on each call, so one handler set answers every request.\n const asking: Effect.Effect<P, never, I> = Context.isKey(principal)\n ? principal\n : Effect.succeed(principal)\n return {\n FoldkitRemoteRead: Effect.fn('RemoteServer.FoldkitRemoteRead')(function* (payload) {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return yield* mismatch\n const caller = yield* asking\n return yield* RemoteServer.readHelper(server, caller, options, payload.requests)\n }),\n\n FoldkitRemoteMutate: Effect.fn('RemoteServer.FoldkitRemoteMutate')(function* (payload) {\n const source = server.mutations.get(payload.mutation)\n if (source === undefined) {\n return yield* new RemoteMutationError({\n message: `Unknown mutation: ${payload.mutation}`,\n })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation input' })),\n ),\n )\n\n const caller = yield* asking\n const outcome = yield* source\n .run({\n input,\n principal: caller,\n requestId: payload.requestId,\n operation: Option.fromUndefinedOr(payload.operation),\n keys: payload.keys,\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n Effect.catchTag('MutationRefused', refused =>\n refusalError(source.Refusal, payload.mutation, refused),\n ),\n )\n\n const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation output' })),\n ),\n )\n\n // What the mutation answers is what changed, so live subscribers hear it\n // without the handler naming it again. The write has committed by now: a\n // failed publish is logged, never the mutation's failure, which a client\n // would retry.\n const hub = options.live\n if (hub !== undefined) {\n // A declared write's answer is the row as stored; a handler's is its own claim.\n const stored = source.writes !== undefined\n yield* Effect.forEach(outcome.entities, patch =>\n hub.changed(\n { entity: patch.entity, id: patch.id },\n Object.keys(patch.values),\n stored ? patch.values : undefined,\n ),\n ).pipe(\n Effect.andThen(Effect.forEach(outcome.deleted, gone => hub.deleted(gone))),\n Effect.catchCause(cause =>\n Effect.logWarning(\n 'RemoteServer: a mutation committed but its live publish failed',\n cause,\n ),\n ),\n )\n }\n\n return {\n output,\n entities: outcome.entities.map(patch => ({\n entity: patch.entity,\n id: patch.id,\n values: patch.values,\n })),\n connections: outcome.connections,\n deleted: outcome.deleted.map(gone => ({ entity: gone.entity, id: gone.id })),\n }\n }),\n\n FoldkitRemoteQuery: Effect.fn('RemoteServer.FoldkitRemoteQuery')(function* (payload) {\n const source = server.queries.get(payload.query)\n if (source === undefined) {\n return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteQueryError({ message: 'Invalid query input' })),\n ),\n )\n\n const select = payload.select\n if (select !== undefined) {\n const paged = checkPagesPerRelation([select])\n if (paged !== undefined) {\n return yield* new RemoteQueryError({\n message: `Too many pages of \"${paged}\" in one query select`,\n })\n }\n }\n\n const caller = yield* asking\n const page = yield* source\n .run({\n input,\n window: payload.window,\n principal: caller,\n ...(select === undefined ? {} : { select }),\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n\n if (select === undefined) return { edges: page.edges, start: page.start, end: page.end }\n // The page's items as requirements, so the selected fields ride back\n // with the edges in one response. Edges of another entity (a query\n // lists one) take no fields: the client's planner asks for them next.\n const requirements: Requirement[] = page.edges.flatMap(edge =>\n edge.entity === select.entity\n ? [\n {\n entity: select.entity,\n id: edge.id,\n fields: [...select.fields],\n ...(select.windows === undefined ? {} : { windows: select.windows }),\n ...(select.relations === undefined ? {} : { relations: select.relations }),\n },\n ]\n : [],\n )\n if (requirements.length === 0)\n return { edges: page.edges, start: page.start, end: page.end, entities: [], settled: [] }\n const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(\n Effect.catchTag('RemoteReadError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n return { edges: page.edges, start: page.start, end: page.end, ...read }\n }),\n\n FoldkitRemoteLive: payload => {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return Stream.fail(mismatch)\n return Stream.unwrap(\n Effect.map(asking, caller => {\n const entities = [...new Set(payload.requirements.map(request => request.entity))]\n const streams: Array<Stream.Stream<LiveChangeValue, RemoteServerError, R>> =\n entities.flatMap(entity => {\n const source = server.live.get(entity)\n if (source === undefined) return []\n return [\n source.subscribe({\n requirements: payload.requirements.filter(request => request.entity === entity),\n after: payload.after,\n principal: caller,\n }),\n ]\n })\n if (options.live !== undefined) {\n streams.push(\n options.live.subscribe({\n requirements: payload.requirements,\n after: payload.after,\n principal: caller,\n maxIdsPerEntity: options.maxIdsPerEntity,\n }),\n )\n }\n // An entity with no live source simply contributes nothing; the client's\n // planner refetches it rather than the stream failing.\n return Stream.mergeAll(streams, { concurrency: 'unbounded' }).pipe(\n Stream.mapError(error => new RemoteLiveError({ message: error.message })),\n )\n }),\n )\n },\n }\n },\n}\n\nexport * from './evaluate.js'\n"],"mappings":";;;;;AAGA,MAAa,yBAAyB,aACnC;CACC,QAAQ;CACR,MAAM;EACJ,OAAO,QAAQ;EACf,iBAAiB,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CAChF;AACF;;;;;;;;;AC+DF,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;;;;;;AAOH,IAAa,cAAb,cAAiC,OAAO,YAAyB,CAAC,CAAC,eAAe,EAChF,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQJ,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB;CACtF,SAAS,OAAO;CAChB,MAAM,OAAO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|
|
4
4
|
"description": "Server sources and handler compilation for foldkit-remote: entities, selection authorization, and normalization.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -49,8 +49,8 @@
|
|
|
49
49
|
"LICENSE"
|
|
50
50
|
],
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"foldkit-entity": "0.
|
|
53
|
-
"foldkit-remote": "0.
|
|
52
|
+
"foldkit-entity": "0.13.0",
|
|
53
|
+
"foldkit-remote": "0.21.0"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
56
|
"effect": "^4.0.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-n8siUL2f.mjs","names":[],"sources":["../src/refusal.ts","../src/index.ts"],"sourcesContent":["import type { RemoteJsonAnswer, RemoteUnauthenticated } from 'foldkit-remote'\n\n/** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */\nexport const unauthenticatedAnswer = (refusal: RemoteUnauthenticated) =>\n ({\n status: 401,\n body: {\n error: refusal.message,\n unauthenticated: refusal.reason === undefined ? {} : { reason: refusal.reason },\n } satisfies RemoteJsonAnswer,\n }) as const\n","/**\n * `foldkit-remote-server` — server-side Sources and handler compilation.\n *\n * Owns entity/query Sources, **selection authorization**, normalization, and\n * turning them into Effect RPC handlers. It does not own HTTP, serialization, or\n * auth protocol; `principal` is resolved outside, and passed in or provided.\n */\nimport { Context, Effect, Layer, Match, Option, Queue, Schema, Stream } from 'effect'\nimport {\n Entity,\n Write,\n evaluate,\n type AnyQuery,\n type AnyWrite,\n type BoundWrite,\n type EntityRef,\n type Row,\n} from 'foldkit-entity'\nimport {\n REMOTE_PROTOCOL_VERSION,\n Remote,\n RemoteClient,\n RemoteForbidden,\n RemoteUnauthenticated,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n connectionIdentity,\n entityKey,\n refParts,\n refsIn,\n relationShape,\n stableStringify,\n type Boundary,\n type ConnectionChangeSchema,\n type ConnectionIdentity,\n type LiveChange,\n type MutationDescriptor,\n type NormalizedPatch,\n type QueryDescriptor,\n type QueryWindow,\n type RelationRequirement,\n type RemoteDescriptor,\n Requirement,\n type RemoteRpcClient,\n MutationRequest,\n QueryRequest,\n ReadBatch,\n RemoteJsonAnswer,\n RemoteJsonRequest,\n RELATION_ALIAS,\n aliasedField,\n} from 'foldkit-remote'\nimport { unauthenticatedAnswer } from './refusal.js'\n\n/** What a call `RemoteServer.answer` makes can fail with, before the answer says so. */\ntype AnswerError =\n | Schema.SchemaError\n | RemoteUnauthenticated\n | RemoteReadError\n | RemoteQueryError\n | RemoteMutationError\n | RemoteForbidden\n | RemoteProtocolError\n\nexport class RemoteServerError extends Schema.TaggedError<RemoteServerError>()(\n 'RemoteServerError',\n {\n message: Schema.String,\n },\n) {}\n\n/**\n * A writer's word that the row does not hold what the write's `when` asks of\n * it, where the write would commit: `RemoteServer.write` answers it as the\n * mutation's `Unmet` refusal.\n */\nexport class RemoteUnmet extends Schema.TaggedError<RemoteUnmet>()('RemoteUnmet', {\n message: Schema.String,\n}) {}\n\n/**\n * A writer's word that the row a write would leave breaks one of its Entity's\n * invariants: `RemoteServer.write` answers it as the mutation's `Invalid`\n * refusal. `rule` and `path` are none and empty when saying them would tell\n * the caller what a member hidden from them holds.\n */\nexport class RemoteInvalid extends Schema.TaggedError<RemoteInvalid>()('RemoteInvalid', {\n message: Schema.String,\n rule: Schema.Option(Schema.String),\n path: Schema.Array(Schema.String),\n}) {}\n\n/** A write's precondition as a writer is handed it: the body, and the input encoded. */\nexport interface WriteWhen {\n readonly body: AnyQuery\n readonly input: Readonly<Record<string, unknown>>\n}\n\n/**\n * A mutation Source's refusal, as the value its descriptor's `Refusal`\n * declares: made with `RemoteServer.refuse`, which checks the value's type\n * against the mutation, and sent to the client encoded, beside a message.\n */\nexport class MutationRefused extends Schema.TaggedError<MutationRefused>()('MutationRefused', {\n /** The mutation the refusal was made for: a Source refusing as another is a bug. */\n mutation: Schema.String,\n refusal: Schema.Unknown,\n /** What a person reads: the error's message beside the refusal. */\n message: Schema.String,\n}) {}\n\nexport interface EntityRecord {\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n}\n\nexport interface EntitySourceContext<P> {\n readonly ids: readonly string[]\n readonly fields: readonly string[]\n /** A pagination window per requested relation field. */\n readonly windows?: Readonly<Record<string, QueryWindow>> | undefined\n readonly principal: P\n}\n\nexport interface EntitySource<P, R = never> {\n readonly entity: string\n /** The fields the entity declares; a request for any other never reaches `read`. */\n readonly fields?: ReadonlySet<string> | undefined\n readonly read: (\n context: EntitySourceContext<P>,\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>\n /** Returns the fields this principal may read; omitted means all requested. */\n readonly authorize?: (principal: P, fields: readonly string[]) => readonly string[]\n /**\n * Decides, per record, what a principal sees of the fields `authorize`\n * allowed: run once per read, before `read`. A member it drops from a\n * record is settled unread, as one the source did not return.\n */\n readonly filter?: (\n principal: P,\n fields: readonly string[],\n ) => Effect.Effect<ReadPlan, RemoteServerError, R>\n /**\n * The rule that decides which rows this source returns, as it was given one\n * (a Drizzle binding's `visible`, `RemoteServer.memory`'s `readable`). The\n * server never runs it: it is here so a check at startup, such as\n * `GuardServer.validate`, can confirm a source applies the rule its Entity\n * requires.\n */\n readonly visible?: unknown\n /**\n * The fields every principal reads alike, of every row: no rule about who\n * is asking hides the row or the field, or changes its value. A promise the\n * server keeps by trusting it: the live hub sends a declared write's value\n * of one to every subscriber as it is, with no read per principal.\n */\n readonly shared?: ReadonlySet<string> | undefined\n}\n\n/** What `EntitySource.filter` decides for one read. */\nexport interface ReadPlan {\n /** The fields to read: those allowed, and any the decision itself needs. */\n readonly fields: readonly string[]\n /** One record as the principal sees it: a member dropped, or its value replaced. */\n readonly apply: (record: EntityRecord) => EntityRecord\n}\n\n/** `source.read` of `fields`, through the source's `filter` when it has one. */\nconst readFiltered = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: readonly string[],\n read: (\n fields: readonly string[],\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>,\n): Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R> =>\n source.filter === undefined\n ? read(fields)\n : Effect.flatMap(source.filter(principal, fields), plan =>\n Effect.map(read(plan.fields), records => records.map(plan.apply)),\n )\n\n/**\n * Where a declared write lands: one row's new values, encoded as the store holds\n * them. With `expect`, the row is written only while its revision is still that\n * value, and the revision moves on with the write. With `when`, only while the\n * row holds its body, checked in the statement that writes it; a row there at\n * the expected revision that does not hold it fails with `RemoteUnmet`. The row\n * as written answers; none when no row matched.\n */\nexport interface EntityWriter<P, R = never> {\n readonly entity: string\n /**\n * Whether `update` and `delete` honour `when`. `RemoteServer.write` refuses\n * a write with a precondition over a writer without it, which would write\n * whatever the row held.\n */\n readonly preconditions?: true\n /**\n * Whether `update` adds `increments` to their fields where it writes.\n * `RemoteServer.write` refuses a write with an increment over a writer\n * without it, which would leave the fields where they were.\n */\n readonly increments?: true\n /**\n * Whether `update` records each write it lands under its `operation`, in\n * the transaction that writes, and answers a retry of it from that record\n * rather than writing again. An increment that expects no revision needs one.\n */\n readonly ledger?: true\n /**\n * Whether `update` and `insert` refuse a row, or a change, that would break\n * one of its Entity's invariants (`Entity.invariant`), with `RemoteInvalid`,\n * judged over the rows they write; an insert judges the state invariants\n * alone. `RemoteServer.write` refuses a write the Entity holds to any through\n * a writer without it.\n */\n readonly invariants?: true\n /**\n * The answer recorded for `operation`, when this writer has a ledger and\n * holds one: what a wrapping writer (a guard) answers a retry with, without\n * deciding again over a row that has moved since.\n */\n readonly recorded?: (context: {\n readonly operation: string\n /** The row the operation writes: one operation may write several rows. */\n readonly id: string\n readonly principal: P\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n readonly update: (context: {\n readonly id: string\n /** The operation's identity across clients, when the client sent one: a ledger's key. */\n readonly operation: Option.Option<string>\n readonly values: Readonly<Record<string, unknown>>\n /**\n * Each field to move, by the amount, encoded: added to the stored value in\n * the statement that writes, never computed from a value read before it.\n */\n readonly increments: Readonly<Record<string, number>>\n /** Each `one` relation it points, by the relation's key: the row, or none. */\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n readonly expect: Option.Option<{ readonly field: string; readonly revision: unknown }>\n readonly when: Option.Option<WriteWhen>\n readonly principal: P\n }) => Effect.Effect<\n Option.Option<Readonly<Record<string, unknown>>>,\n RemoteServerError | RemoteForbidden | RemoteUnmet | RemoteInvalid,\n R\n >\n /**\n * Inserts the row, or finds one already there under that id holding what\n * it writes (a retry); answers the row as it is. Fails when the id holds\n * any other row.\n */\n readonly insert: (context: {\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n readonly links: Readonly<Record<string, Option.Option<EntityRef>>>\n readonly principal: P\n }) => Effect.Effect<\n Readonly<Record<string, unknown>>,\n RemoteServerError | RemoteForbidden | RemoteInvalid,\n R\n >\n /**\n * Deletes the row, while it is still at the revision when one is expected:\n * `deleted`, `absent` (no row, so nothing to delete; a retry's case), or\n * `moved` (the row is there at another revision, and stays).\n */\n readonly delete: (context: {\n readonly id: string\n readonly expect: Option.Option<{ readonly field: string; readonly revision: unknown }>\n readonly when: Option.Option<WriteWhen>\n readonly principal: P\n }) => Effect.Effect<\n 'deleted' | 'absent' | 'moved',\n RemoteServerError | RemoteForbidden | RemoteUnmet,\n R\n >\n /**\n * The row as `principal` may see it, under the read rule its Source applies:\n * none when there is no such row, or it is hidden. Given, a write's answer\n * is read back through it, so an answer never shows its writer a row it may\n * not read, and a row the write hid from them answers as deleted.\n */\n readonly read?: (context: {\n readonly id: string\n readonly fields: ReadonlyArray<string>\n readonly principal: P\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n /**\n * Each of `relations`' links as stored, by ref key (`'Project:p1'`) or\n * `null`, whatever a reader may see of the row it points at; none when there\n * is no such row. A guard reads it to tell a write that unlinks a row hidden\n * from its writer from one that changes nothing.\n */\n readonly linked?: (context: {\n readonly id: string\n readonly relations: ReadonlyArray<string>\n }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>\n}\n\n/** A connection change a mutation made, as the wire carries it. */\nexport type ConnectionChange = Schema.Schema.Type<typeof ConnectionChangeSchema>\n\nconst connectionChange = (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n position: 'prepend' | 'append' | 'remove',\n): ConnectionChange => {\n const edge = { entity: ref.entity, id: ref.id, key: entityKey(ref.entity, ref.id) }\n return position === 'remove'\n ? { _tag: 'Remove', connection: connectionIdentity(connection), edge }\n : { _tag: 'Insert', connection: connectionIdentity(connection), position, edge }\n}\n\n/**\n * The requested fields, in request order, that the source declares and the\n * principal may read. Never a field the client did not request, even if a\n * permissive `authorize` returns more.\n */\nconst allowedFields = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n requested: ReadonlyArray<string>,\n): ReadonlyArray<string> => {\n const declared =\n source.fields === undefined ? requested : requested.filter(field => source.fields!.has(field))\n if (declared.length === 0) return []\n const permitted = new Set(\n source.authorize === undefined ? declared : source.authorize(principal, declared),\n )\n return declared.filter(field => permitted.has(field))\n}\n\n/** The windows of the fields being read; only a field being read carries its window. */\nconst windowsOf = (\n windows: Readonly<Record<string, QueryWindow>> | undefined,\n fields: ReadonlyArray<string>,\n): { readonly windows?: Readonly<Record<string, QueryWindow>> } => {\n if (windows === undefined) return {}\n const kept = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(windows, field) ? [[field, windows[field]!] as const] : [],\n ),\n )\n return Object.keys(kept).length === 0 ? {} : { windows: kept }\n}\n\nexport interface MutationOutcome<Output> {\n readonly output: Output\n readonly entities?: ReadonlyArray<NormalizedPatch>\n /** Connection changes the mutation made; the client settles them with its patches. */\n readonly connections?: ReadonlyArray<ConnectionChange>\n /**\n * Entities the mutation deleted. The client knows them absent from then on:\n * they leave every connection and read `NotFound`, with no connection to name.\n */\n readonly deleted?: ReadonlyArray<{ readonly entity: string; readonly id: string }>\n}\n\nexport interface MutationSource<P, R = never> {\n readonly mutation: string\n /**\n * For a declared write (`RemoteServer.write`), the Entity it writes, the\n * writer it lands through, as it was given one, and the write itself. The\n * server never reads it; a startup check such as `GuardServer.validate` does.\n */\n readonly writes?: { readonly entity: string; readonly writer: unknown; readonly write: AnyWrite }\n readonly Input: Schema.Codec<unknown>\n readonly Output: Schema.Codec<unknown>\n readonly Refusal: Schema.Codec<unknown, unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly principal: P\n /**\n * The client's id for this request, the same on every retry of it. It is\n * unique within that client only: two clients' first requests can share\n * it. Key a record of the write by `operation`, never by this.\n */\n readonly requestId: string\n /**\n * The operation's identity across clients, the same on every retry of it,\n * when the client sent one (Remote's does); none from an older client.\n */\n readonly operation: Option.Option<string>\n /** For a declared write: the input keys to write, when the client named only some. */\n readonly keys?: ReadonlyArray<string> | undefined\n }) => Effect.Effect<\n {\n readonly output: unknown\n readonly entities: ReadonlyArray<NormalizedPatch>\n readonly connections: ReadonlyArray<ConnectionChange>\n readonly deleted: ReadonlyArray<{ readonly entity: string; readonly id: string }>\n },\n RemoteServerError | MutationRefused | RemoteForbidden,\n R\n >\n}\n\nexport interface QueryPage {\n readonly edges: ReadonlyArray<{\n readonly entity: string\n readonly id: string\n readonly key: string\n }>\n readonly start: Boundary\n readonly end: Boundary\n}\n\nexport interface QuerySource<P, R = never> {\n readonly query: string\n readonly Input: Schema.Codec<unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly window: QueryWindow\n readonly principal: P\n /**\n * What the client reads of each item. A source may use it to answer\n * fields with the page, or ignore it: the handlers fetch what the page\n * leaves out through the entity sources, so one response still carries\n * both either way.\n */\n readonly select?: RelationRequirement | undefined\n }) => Effect.Effect<QueryPage, RemoteServerError, R>\n /** The rule that decides which rows the query lists. See `EntitySource.visible`. */\n readonly visible?: unknown\n}\n\nexport interface LiveSource<P, R = never> {\n readonly entity: string\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n }) => Stream.Stream<Schema.Schema.Type<typeof LiveChange>, RemoteServerError, R>\n}\n\nexport interface ServerDefinition<P, R = never> {\n readonly entities: ReadonlyMap<string, EntitySource<P, R>>\n readonly mutations: ReadonlyMap<string, MutationSource<P, R>>\n readonly queries: ReadonlyMap<string, QuerySource<P, R>>\n readonly live: ReadonlyMap<string, LiveSource<P, R>>\n}\n\n/** A read batch may not carry more than this many distinct ids per entity. */\nconst DEFAULT_MAX_IDS_PER_ENTITY = 1000\n\n/** A nested selection may not reach further than this many relation levels. */\nconst DEFAULT_MAX_DEPTH = 8\n\nexport interface HandlerOptions<P, R = never> {\n /** A read or live subscription may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many relation levels; default 8. */\n readonly maxDepth?: number | undefined\n /** A hub whose `changed`/`deleted` signals reach the subscribers this handler registers. */\n readonly live?: LiveHub<P, R> | undefined\n}\n\n/** Fails when the requirements name more distinct ids of one entity than `maxIds`. */\n/**\n * Each page of a relation read beside another is a source read of its own, and\n * the names come from the client, so how many one relation may have is bounded.\n * A screen shows a list and a page or two of it, not dozens.\n */\nconst MAX_PAGES_PER_RELATION = 4\n\n/** The relation a request pages more ways than allowed, at any depth; `undefined` when none. */\nconst checkPagesPerRelation = (\n requirements: ReadonlyArray<RelationRequirement>,\n): string | undefined => {\n for (const requirement of requirements) {\n const pages = new Map<string, number>()\n for (const name of requirement.fields) {\n if (!name.includes(RELATION_ALIAS)) continue\n const field = aliasedField(name)\n const count = (pages.get(field) ?? 0) + 1\n if (count > MAX_PAGES_PER_RELATION) return `${requirement.entity}.${field}`\n pages.set(field, count)\n }\n const nested = checkPagesPerRelation(Object.values(requirement.relations ?? {}))\n if (nested !== undefined) return nested\n }\n return undefined\n}\n\nconst checkIdsPerEntity = (\n requirements: ReadonlyArray<Requirement>,\n maxIds: number,\n): string | undefined => {\n const ids = new Map<string, Set<string>>()\n for (const requirement of requirements) {\n const seen = ids.get(requirement.entity) ?? new Set<string>()\n seen.add(requirement.id)\n ids.set(requirement.entity, seen)\n if (seen.size > maxIds) return requirement.entity\n }\n return undefined\n}\n\ntype LiveChangeValue = Schema.Schema.Type<typeof LiveChange>\ntype Uncursored<T> = T extends unknown ? Omit<T, 'cursor'> : never\n\ninterface LiveRef {\n readonly entity: string\n readonly id: string\n}\n\n/**\n * The server-side \"these fields changed\" signal. A hub tracks each live\n * subscriber's requirements (entity, id, fields) and principal; `changed`\n * re-reads the changed fields a subscriber selects through the entity's own\n * source, under that subscriber's principal, and streams the patch to it.\n * Subscribers that select none of the changed fields do no work. Cursors\n * continue from the cursor each subscriber resumed at, so the client's\n * duplicate and gap handling is unchanged.\n */\nexport interface LiveHub<P, R = never> {\n /**\n * `values`, when given, are the row's stored values of `fields` (a declared\n * write's answer): a field of them the source declares `shared` is sent as\n * it is, and only the rest are re-read.\n */\n readonly changed: (\n ref: LiveRef,\n fields: ReadonlyArray<string>,\n values?: Readonly<Record<string, unknown>> | undefined,\n ) => Effect.Effect<void, RemoteServerError, R>\n /**\n * `ref` may be gone: each subscriber's selection of it is read again, and\n * one it is no longer there to is sent a deletion. A row deleted for one\n * writer may only be hidden from them, and still there to others.\n */\n readonly deleted: (ref: LiveRef) => Effect.Effect<void, RemoteServerError, R>\n /** Registers a subscriber for the stream's lifetime; `handlers` calls this. */\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n /** Refuses a subscription naming more ids of one entity than this. */\n readonly maxIdsPerEntity?: number | undefined\n }) => Stream.Stream<LiveChangeValue, RemoteServerError>\n /** How many subscribers are registered now. */\n readonly size: Effect.Effect<number>\n}\n\ninterface Selected {\n readonly fields: Set<string>\n /** The window each paged field was subscribed with, so a re-read pages the same way. */\n readonly windows: Map<string, QueryWindow>\n}\n\n/** The subscribers one source read answers, and the fields each wants of it. */\ninterface ReadGroup<P> {\n readonly windows: Readonly<Record<string, QueryWindow>>\n /** The alias each field read here is answered under. */\n readonly renames: Readonly<Record<string, string>>\n readonly entries: Array<{ readonly subscriber: Subscriber<P>; readonly fields: string[] }>\n}\n\ninterface Subscriber<P> {\n /** Per entity:id, the fields (and their windows) this subscriber selects. */\n readonly selected: ReadonlyMap<string, Selected>\n readonly principal: P\n readonly queue: Queue.Queue<LiveChangeValue>\n cursor: number\n}\n\nconst liveHub = <P, R>(\n entities: ReadonlyArray<EntitySource<P, R>>,\n options: {\n /**\n * Who a principal is, for sharing re-reads: subscribers whose principals\n * have one key share one read, under the first one's principal. Default:\n * the principal itself, so only the same value shares.\n */\n readonly key?: ((principal: P) => unknown) | undefined\n } = {},\n): Effect.Effect<LiveHub<P, R>> =>\n Effect.sync(() => {\n const keyOf = options.key ?? ((principal: P): unknown => principal)\n const sources = new Map(entities.map(source => [source.entity, source]))\n const subscribers = new Set<Subscriber<P>>()\n const emit = (subscriber: Subscriber<P>, change: Uncursored<LiveChangeValue>) => {\n subscriber.cursor += 1\n return Queue.offer(subscriber.queue, {\n ...change,\n cursor: subscriber.cursor,\n } as LiveChangeValue)\n }\n\n /**\n * Re-reads row `ref` for each subscriber that selects it, of `which` of\n * its fields (none: every field it selects), and sends what it now sees:\n * a patch, or, where the row is no longer there to it, a deletion. One\n * group's failed read fails the call after the others are sent.\n */\n const refresh = (\n ref: LiveRef,\n which: Option.Option<ReadonlyArray<string>>,\n values: Readonly<Record<string, unknown>> | undefined,\n ): Effect.Effect<void, RemoteServerError, R> =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n const source = sources.get(ref.entity)\n if (source === undefined) {\n // Nothing to ask: a deletion reaches every subscriber as it is.\n if (Option.isSome(which)) return\n for (const subscriber of subscribers) {\n if (subscriber.selected.has(key))\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n }\n return\n }\n // A shared field's written value is every subscriber's alike: it needs no read.\n const given = (field: string) =>\n values !== undefined &&\n source.shared !== undefined &&\n source.shared.has(field) &&\n Object.hasOwn(values, field)\n // One source read per principal key and window signature:\n // subscribers sharing both share the read, and a paged field is\n // re-read with the window the subscriber selected it with.\n const groups = new Map<\n unknown,\n { readonly principal: P; readonly byWindows: Map<string, ReadGroup<P>> }\n >()\n for (const subscriber of subscribers) {\n const selected = subscriber.selected.get(key)\n if (selected === undefined) continue\n const fields = Option.getOrElse(which, () => [\n ...new Set([...selected.fields].map(aliasedField)),\n ])\n const principalKey = keyOf(subscriber.principal)\n const sharing = groups.get(principalKey) ?? {\n principal: subscriber.principal,\n byWindows: new Map<string, ReadGroup<P>>(),\n }\n groups.set(principalKey, sharing)\n const { byWindows } = sharing\n const join = (\n windows: Readonly<Record<string, QueryWindow>>,\n renames: Readonly<Record<string, string>>,\n wanted: string[],\n ): void => {\n const groupKey = `${stableStringify(windows)}\\u0000${stableStringify(renames)}`\n const group = byWindows.get(groupKey) ?? { windows, renames, entries: [] }\n byWindows.set(groupKey, group)\n group.entries.push({ subscriber, fields: wanted })\n }\n const selects = fields.filter(field => selected.fields.has(field))\n // A paged field is read with its subscriber's window, so it is never sent as written.\n const sent = selects.filter(field => given(field) && !selected.windows.has(field))\n if (sent.length > 0) {\n const patch: Record<string, unknown> = Object.create(null)\n for (const field of sent) patch[field] = values![field]\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values: patch,\n changed: sent,\n })\n }\n const sentSet = new Set(sent)\n const wanted = selects.filter(field => !sentSet.has(field))\n if (wanted.length > 0)\n join(\n Object.fromEntries(\n wanted.flatMap(field => {\n const window = selected.windows.get(field)\n return window === undefined ? [] : [[field, window] as const]\n }),\n ),\n {},\n wanted,\n )\n // A page read under an alias changes when the relation it reads does, and\n // is re-read on its own, with its window, so the whole list can be too.\n for (const alias of selected.fields) {\n const window = selected.windows.get(alias)\n const field = aliasedField(alias)\n if (field === alias || window === undefined || !fields.includes(field)) continue\n join({ [field]: window }, { [field]: alias }, [field])\n }\n }\n const gone = new Set<Subscriber<P>>()\n const read = (\n principal: P,\n { windows, renames, entries: group }: ReadGroup<P>,\n ): Effect.Effect<void, RemoteServerError, R> =>\n Effect.gen(function* () {\n const requested = [...new Set(group.flatMap(entry => entry.fields))]\n const allowed = allowedFields(source, principal, requested)\n if (allowed.length === 0) return\n const allowedSet = new Set(allowed)\n const records = yield* readFiltered(source, principal, allowed, fields =>\n source.read({ ids: [ref.id], fields, principal, ...windowsOf(windows, allowed) }),\n )\n const record = records.find(candidate => candidate.id === ref.id)\n for (const { subscriber, fields: wanted } of group) {\n if (gone.has(subscriber)) continue\n if (record === undefined) {\n // Deleted, or no longer there to this principal: either way, gone.\n gone.add(subscriber)\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n continue\n }\n const values: Record<string, unknown> = Object.create(null)\n for (const field of wanted) {\n if (allowedSet.has(field) && Object.hasOwn(record.values, field)) {\n values[renamed(renames, field)] = record.values[field]\n }\n }\n const changed = Object.keys(values)\n if (changed.length === 0) continue\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values,\n changed,\n })\n }\n })\n const failures: Array<RemoteServerError> = []\n for (const { principal, byWindows } of groups.values()) {\n for (const group of byWindows.values()) {\n yield* read(principal, group).pipe(\n Effect.catch(error => Effect.sync(() => void failures.push(error))),\n )\n }\n }\n if (failures.length > 0) return yield* Effect.fail(failures[0]!)\n })\n\n return {\n subscribe: ({ requirements, after, principal, maxIdsPerEntity }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const over = checkIdsPerEntity(\n requirements,\n Math.max(1, maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY),\n )\n if (over !== undefined) {\n return yield* new RemoteServerError({\n message: `Too many \"${over}\" ids in one live subscription`,\n })\n }\n const paged = checkPagesPerRelation(requirements)\n if (paged !== undefined) {\n return yield* new RemoteServerError({\n message: `Too many pages of \"${paged}\" in one live subscription`,\n })\n }\n const selected = new Map<string, Selected>()\n for (const requirement of requirements) {\n const key = `${requirement.entity}:${requirement.id}`\n const entry = selected.get(key) ?? { fields: new Set<string>(), windows: new Map() }\n for (const field of requirement.fields) entry.fields.add(field)\n for (const [field, window] of Object.entries(requirement.windows ?? {})) {\n entry.windows.set(field, window)\n }\n selected.set(key, entry)\n }\n const subscriber: Subscriber<P> = {\n selected,\n principal,\n queue: yield* Queue.unbounded<LiveChangeValue>(),\n cursor: after,\n }\n subscribers.add(subscriber)\n return Stream.fromQueue(subscriber.queue).pipe(\n Stream.ensuring(Effect.sync(() => void subscribers.delete(subscriber))),\n )\n }),\n ),\n\n changed: (ref, fields, values) => refresh(ref, Option.some(fields), values),\n // Gone for one writer may be hidden from them alone: each subscriber is asked again.\n deleted: ref => refresh(ref, Option.none(), undefined),\n\n size: Effect.sync(() => subscribers.size),\n }\n })\n\nconst protocolMismatch = (received: number): RemoteProtocolError | undefined =>\n received === REMOTE_PROTOCOL_VERSION\n ? undefined\n : new RemoteProtocolError({\n message: `Remote protocol version ${received} is not ${REMOTE_PROTOCOL_VERSION}`,\n expected: REMOTE_PROTOCOL_VERSION,\n received,\n })\n\ninterface EntityGroup {\n /** The fields each id was asked for: the union is read, and one id is settled only for its own. */\n readonly ids: Map<string, Set<string>>\n /** The union of the requests' fields, windows, and relations. */\n slice: RelationRequirement\n /** The alias each field read here is answered under; see `RELATION_ALIAS`. */\n readonly renames: Readonly<Record<string, string>>\n}\n\n/** A request, or the part of one that reads a relation under an alias. */\ntype Part = Requirement & { readonly renames?: Readonly<Record<string, string>> }\n\n/**\n * The name a field is answered under. A requested field is client input, so\n * `constructor` must find no rename rather than `Object.prototype`'s.\n */\nconst renamed = (renames: Readonly<Record<string, string>>, field: string): string =>\n Object.hasOwn(renames, field) ? renames[field]! : field\n\nconst pickNames = <T>(\n record: Readonly<Record<string, T>> | undefined,\n names: ReadonlyArray<string>,\n): Readonly<Record<string, T>> | undefined => {\n if (record === undefined) return undefined\n const picked = names.flatMap(name =>\n Object.hasOwn(record, name) ? [[name, record[name]!] as const] : [],\n )\n return picked.length === 0 ? undefined : Object.fromEntries(picked)\n}\n\n/**\n * A request's aliased fields, each as a read of its own. `comments@first=10` is\n * the `comments` relation read with the alias's window, so a source sees the\n * field it knows and one window for it, while the whole list rides beside it in\n * another read. The answer goes back under the alias, which is also the key of\n * the relation followed from it.\n */\nconst splitAliases = (request: Requirement): ReadonlyArray<Part> => {\n const aliases = request.fields.filter(field => field.includes(RELATION_ALIAS))\n if (aliases.length === 0) return [request]\n const plain = request.fields.filter(field => !field.includes(RELATION_ALIAS))\n interface Building {\n fields: string[]\n windows: Record<string, QueryWindow>\n relations: Record<string, RelationRequirement>\n renames: Record<string, string>\n }\n // Keyed by requested field names, so a `__proto__` names an entry, not the prototype.\n const keyed = <T>(entries?: Readonly<Record<string, T>>): Record<string, T> =>\n Object.assign(Object.create(null) as Record<string, T>, entries)\n const first: Building = {\n fields: [...plain],\n windows: keyed(pickNames(request.windows, plain)),\n relations: keyed(pickNames(request.relations, plain)),\n renames: keyed(),\n }\n const building: Building[] = [first]\n for (const alias of aliases) {\n const window = request.windows?.[alias]\n // An alias is a page: one that names no window asks for nothing.\n if (window === undefined) continue\n const field = aliasedField(alias)\n // It rides in a read that does not already read its relation, so a request\n // costs one read unless the list and a page of it are both wanted.\n let part = building.find(candidate => !candidate.fields.includes(field))\n if (part === undefined) {\n part = { fields: [], windows: keyed(), relations: keyed(), renames: keyed() }\n building.push(part)\n }\n part.fields.push(field)\n part.windows[field] = window\n part.renames[field] = alias\n const relation = request.relations?.[alias]\n if (relation !== undefined) part.relations[alias] = relation\n }\n return building\n .filter(part => part.fields.length > 0)\n .map(part => ({\n entity: request.entity,\n id: request.id,\n fields: part.fields,\n ...(Object.keys(part.windows).length === 0 ? {} : { windows: part.windows }),\n ...(Object.keys(part.relations).length === 0 ? {} : { relations: part.relations }),\n ...(Object.keys(part.renames).length === 0 ? {} : { renames: part.renames }),\n }))\n}\n\n/**\n * One level's requests grouped per entity and window signature: ids and\n * slices unioned. Requests that page a relation differently are separate\n * groups, so one window never answers for another id.\n */\nconst groupByEntity = (requests: ReadonlyArray<Requirement>): EntityGroup[] => {\n const grouped = new Map<string, EntityGroup>()\n for (const request of requests.flatMap(splitAliases)) {\n const renames = request.renames ?? {}\n const groupKey = `${request.entity}\\u0000${stableStringify(request.windows ?? null)}\\u0000${stableStringify(renames)}`\n const group = grouped.get(groupKey)\n if (group === undefined) {\n grouped.set(groupKey, {\n ids: new Map([[request.id, new Set(request.fields)]]),\n slice: Requirement.mergeRelation({ entity: request.entity, fields: [] }, request),\n renames,\n })\n } else {\n const asked = group.ids.get(request.id) ?? new Set<string>()\n for (const field of request.fields) asked.add(field)\n group.ids.set(request.id, asked)\n group.slice = Requirement.mergeRelation(group.slice, request)\n }\n }\n return [...grouped.values()]\n}\n\n/**\n * A descriptor's name and, when it declares them, its readable members: an\n * Entity's `members` (its fields, relations and derived members), or a plain\n * descriptor's `fields`.\n */\ninterface EntityName {\n readonly name: string\n readonly fields?: Readonly<Record<string, unknown>> | undefined\n readonly members?: Readonly<Record<string, unknown>> | undefined\n}\n\n/** One entity's rows in their wire shape: a relation is its ref key, `'User:u1'`. */\nexport type MemoryRows = Readonly<\n Record<string, ReadonlyArray<Readonly<Record<string, unknown>> & { readonly id: string }>>\n>\n\n/**\n * The rows a memory backend holds, which its mutations write through. A\n * change is what the next read sees; nothing is pushed to a client.\n */\nexport interface MemoryStore {\n /** The rows of one entity, in insertion order. */\n readonly rows: (entity: string) => ReadonlyArray<Readonly<Record<string, unknown>>>\n /** Writes these values onto a row, creating it if it is new. */\n readonly write: (entity: string, id: string, values: Readonly<Record<string, unknown>>) => void\n readonly remove: (entity: string, id: string) => void\n}\n\n/**\n * A memory backend made without a `principal`: its rows and the server over\n * them, answered as whoever its caller names per request (`serveFetch`,\n * `RemoteServer.handlers(served.server, principal)`).\n */\nexport interface MemoryServed<P> extends MemoryStore {\n /**\n * The rows' server, for serving them over a real transport, or as any\n * principal: `RemoteRpc.toLayer(RemoteServer.handlers(backend.server, principal))`.\n */\n readonly server: ServerDefinition<P>\n}\n\nexport interface MemoryBackend<P = undefined> extends MemoryServed<P> {\n /**\n * A `RemoteClient` answering from the rows as the configured `principal`.\n * Provide it where the real one would go.\n */\n readonly layer: Layer.Layer<RemoteClient>\n}\n\n/** What `RemoteServer.memory` is made from. See `memory`. */\nexport type MemoryConfig<P> = {\n readonly domain: Pick<RemoteDescriptor, 'registry'>\n readonly rows: MemoryRows\n /**\n * Sources for entities the domain does not declare, which no row backs (a\n * `Me` row answered from the principal, `GuardServer.me`), served beside\n * the rows. One for a declared entity is refused: the rows serve it.\n */\n readonly entities?: ReadonlyArray<EntitySource<P>>\n /** Sources for queries, beside the domain's: one named as a declared query answers it instead of its body. */\n readonly queries?: ReadonlyArray<QuerySource<P>>\n readonly mutations?: (store: MemoryStore) => ReadonlyArray<MutationSource<P>>\n /** Per entity name, the fields a principal may read, as `RemoteServer.entity` takes it. */\n readonly authorize?: Readonly<Record<string, NonNullable<EntitySource<P>['authorize']>>>\n /** Per entity name, what a principal sees of each record, as `RemoteServer.entity` takes it. */\n readonly filter?: Readonly<Record<string, NonNullable<EntitySource<P>['filter']>>>\n /** Per entity name, the fields every principal reads alike: see `EntitySource.shared`. */\n readonly shared?: Readonly<Record<string, ReadonlyArray<string>>>\n /**\n * Which stored rows a principal may read, decided once per read. A row it\n * may not read is absent from a read by id and from every query, and a ref\n * to one is dropped from a relation (a `one` ref reads as `null`). `row`\n * looks another stored row up, for a decision that follows a relation.\n */\n readonly readable?: (\n principal: P,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ) => Effect.Effect<MemoryReadable, RemoteServerError>\n /** Who the `layer` answers as. Without it there is no `layer`, unless `P` admits `undefined`. */\n readonly principal?: P\n}\n\n/** What a backend needs to give a `layer`: a principal to answer as, or one `undefined` can be. */\nexport type MemoryAnswering<P> = undefined extends P ? unknown : { readonly principal: P }\n\n/** Whether a stored row of `entity` may be read, given its whole stored values. */\nexport type MemoryReadable = (entity: string, row: Readonly<Record<string, unknown>>) => boolean\n\n/** Where a cursor falls among ordered items: before `index`, or at it when `exact`. */\ninterface Position {\n readonly index: number\n readonly exact: boolean\n}\n\n/**\n * One page of ordered items for a window, as a real server pages them. A\n * cursor is an item's id: a forward page starts at the `after` it was asked\n * for and ends at its last item while more follow, a backward page the\n * mirror, so a page fetched from another's end cursor joins it.\n *\n * `locate` places a cursor that is not among the items, as a keyset does: a\n * row that stopped matching still has a place in the order. Without it, such\n * a cursor is an error. A page of no items has no id of its own to end at, so\n * with more beyond it and no cursor to repeat, its boundary is `Unknown`.\n */\nconst pageOf = <Item>(\n items: ReadonlyArray<Item>,\n window: QueryWindow,\n idOf: (item: Item) => string,\n locate?: (cursor: string) => Position,\n): { readonly items: ReadonlyArray<Item>; readonly start: Boundary; readonly end: Boundary } => {\n if (\n (window.after !== undefined && window.before !== undefined) ||\n (window.first !== undefined && window.last !== undefined)\n ) {\n throw new Error('A query window cannot combine after with before, or first with last')\n }\n const position = (cursor: string): Position => {\n const index = items.findIndex(item => idOf(item) === cursor)\n if (index >= 0) return { index, exact: true }\n if (locate !== undefined) return locate(cursor)\n throw new Error(`Cursor \"${cursor}\" names nothing in these results`)\n }\n const cursor = (id: string): Boundary => ({ _tag: 'Cursor', cursor: id })\n const terminal: Boundary = { _tag: 'Terminal' }\n const unknown: Boundary = { _tag: 'Unknown' }\n if (window.last !== undefined || window.before !== undefined) {\n const to = window.before === undefined ? items.length : position(window.before).index\n const from = window.last === undefined ? 0 : Math.max(0, to - window.last)\n const page = items.slice(from, to)\n const start =\n from === 0\n ? terminal\n : page.length > 0\n ? cursor(idOf(page[0]!))\n : window.before === undefined\n ? unknown\n : cursor(window.before)\n return {\n items: page,\n start,\n end: window.before === undefined ? terminal : cursor(window.before),\n }\n }\n const at = window.after === undefined ? undefined : position(window.after)\n const from = at === undefined ? 0 : at.exact ? at.index + 1 : at.index\n const to = window.first === undefined ? items.length : Math.min(items.length, from + window.first)\n const page = items.slice(from, to)\n const end =\n to >= items.length\n ? terminal\n : page.length > 0\n ? cursor(idOf(page.at(-1)!))\n : window.after === undefined\n ? unknown\n : cursor(window.after)\n return { items: page, start: window.after === undefined ? terminal : cursor(window.after), end }\n}\n\n/**\n * A backend held in memory: the rows you give it, served through the same\n * handlers a real server uses. For a first run, a test, a story or a demo, with\n * no database and no network.\n *\n * Reads go through `handlers`, so field filtering and nested relations behave\n * as they do in production. A query declared with `Query.define` is answered\n * by running its body over the rows with the reference interpreter, the one\n * every interpreter is held to by the conformance suite. A query with no body\n * has nothing to run and is refused when the backend is made, unless `queries`\n * supplies a source for it. Mutations are yours to give: each one writes\n * through the store it is handed, and the next read sees the change.\n *\n * Every field of every row is readable unless `authorize` names the entity:\n * then its function decides, per principal, as `RemoteServer.entity`'s does.\n * `entities` adds Sources for entities no row backs, which the domain must not\n * declare. The `layer` answers as `principal`, and is absent without one\n * (unless `P` admits `undefined`); `server` answers as any. It does not push\n * live changes. It is not a server to deploy.\n */\nfunction memory<P = undefined>(config: MemoryConfig<P> & MemoryAnswering<P>): MemoryBackend<P>\nfunction memory<P = undefined>(config: MemoryConfig<P>): MemoryServed<P>\nfunction memory<P = undefined>(config: MemoryConfig<P>): MemoryBackend<P> {\n const declared = config.domain.registry.entities\n const extra = new Set<string>()\n for (const source of config.entities ?? []) {\n if (declared.has(source.entity))\n throw new Error(\n `RemoteServer.memory: \"${source.entity}\" is a declared entity, which the rows serve; give its rows, or leave it out of the domain and keep its source`,\n )\n if (extra.has(source.entity))\n throw new Error(`RemoteServer.memory: two sources in \\`entities\\` serve \"${source.entity}\"`)\n extra.add(source.entity)\n }\n const authorize = config.authorize ?? {}\n const filter = config.filter ?? {}\n const shared = config.shared ?? {}\n for (const [option, given] of [\n ['authorize', authorize],\n ['filter', filter],\n ['shared', shared],\n ] as const) {\n const unknown = Object.keys(given).filter(name => !config.domain.registry.entities.has(name))\n if (unknown.length > 0) {\n throw new Error(\n `RemoteServer.memory: \\`${option}\\` names ${unknown.map(name => `\"${name}\"`).join(', ')}, which the domain does not declare`,\n )\n }\n }\n for (const [name, fields] of Object.entries(shared)) {\n const entity: EntityName = config.domain.registry.entities.get(name)!\n const declared = entity.members ?? entity.fields\n const unserved = fields.filter(\n field => declared !== undefined && !Object.hasOwn(declared, field),\n )\n if (unserved.length > 0) {\n throw new Error(\n `RemoteServer.memory: ${name}'s shared fields name no member: ${unserved.join(', ')}`,\n )\n }\n }\n const everyRow: MemoryReadable = () => true\n const readableFor = (principal: P) =>\n config.readable === undefined\n ? Effect.succeed(everyRow)\n : config.readable(principal, (entity, id) => Option.fromUndefinedOr(table(entity).get(id)))\n const tables = new Map<string, Map<string, Record<string, unknown>>>()\n const table = (entity: string) => {\n const existing = tables.get(entity)\n if (existing !== undefined) return existing\n const created = new Map<string, Record<string, unknown>>()\n tables.set(entity, created)\n return created\n }\n for (const [entity, rows] of Object.entries(config.rows)) {\n // Keyed by the id as the wire carries it, a string, whatever JSON gave.\n for (const row of rows) table(entity).set(String(row.id), { ...row })\n }\n const store: MemoryStore = {\n rows: entity => [...table(entity).values()],\n write: (entity, id, values) => {\n table(entity).set(id, { ...table(entity).get(id), id, ...values })\n },\n remove: (entity, id) => {\n table(entity).delete(id)\n },\n }\n\n // A relation page is the refs in a window of the stored list. Its cursor is a\n // ref key, or a bare id, as a real server accepts either.\n const valueFor = (value: unknown, window: QueryWindow | undefined): unknown => {\n if (window === undefined || !Array.isArray(value)) return value\n // A ref listed twice would make a cursor ambiguous, and paging cycle.\n const refs = [...new Set(value as ReadonlyArray<string>)]\n const idOf = (ref: string) => ref.slice(ref.indexOf(':') + 1)\n const named = (cursor: string | undefined) =>\n cursor === undefined ? undefined : cursor.includes(':') ? idOf(cursor) : cursor\n let page: ReturnType<typeof pageOf<string>>\n try {\n page = pageOf(\n refs,\n { ...window, after: named(window.after), before: named(window.before) },\n idOf,\n )\n } catch {\n // A cursor that names nothing in the list answers this one field with an\n // empty page. Failing would fail the whole batch it rode in, every other\n // entity and field with it.\n return { refs: [], hasNext: false, hasPrevious: false }\n }\n // A cursor at either end is exactly \"more lie that way\".\n return {\n refs: page.items,\n hasNext: page.end._tag === 'Cursor',\n hasPrevious: page.start._tag === 'Cursor',\n }\n }\n\n // A relation's value is a ref, or a list of them; a ref to a row the\n // principal may not read is not shown, as a database binding hides it.\n const relationsOf = new Map(\n [...config.domain.registry.entities].map(([name, descriptor]) => [\n name,\n new Set(\n Object.entries(descriptor.fields as Readonly<Record<string, Schema.Top>>).flatMap(\n ([field, schema]) => (relationShape(schema) === undefined ? [] : [field]),\n ),\n ),\n ]),\n )\n const refsShown = (readable: MemoryReadable, entity: string, field: string, value: unknown) => {\n if (readable === everyRow || relationsOf.get(entity)?.has(field) !== true) return value\n const shown = (ref: unknown) => {\n if (typeof ref !== 'string') return true\n const { entity: target, id } = refParts(ref)\n const row = table(target).get(id)\n return row !== undefined && readable(target, row)\n }\n if (Array.isArray(value)) return value.filter(shown)\n return shown(value) ? value : null\n }\n\n // Every row this backend reads, it reads through `readable`.\n const visible = config.readable === undefined ? {} : { visible: config.readable }\n const entities = [...config.domain.registry.entities.keys()].map(name => ({\n ...visible,\n ...RemoteServer.entity<P>(\n { name },\n {\n ...(Object.hasOwn(authorize, name) ? { authorize: authorize[name]! } : {}),\n ...(Object.hasOwn(filter, name) ? { filter: filter[name]! } : {}),\n ...(Object.hasOwn(shared, name) ? { shared: shared[name]! } : {}),\n read: ({ ids, fields, windows, principal }) =>\n Effect.flatMap(readableFor(principal), readable =>\n Effect.try({\n try: () =>\n ids.flatMap(id => {\n const row = table(name).get(id)\n if (row === undefined || !readable(name, row)) return []\n const values = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(row, field)\n ? [\n [\n field,\n valueFor(\n refsShown(readable, name, field, row[field]),\n windows?.[field],\n ),\n ] as const,\n ]\n : [],\n ),\n )\n return [{ id, values }]\n }),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n ),\n },\n ),\n }))\n\n const given = new Set((config.queries ?? []).map(source => source.query))\n const bodiless = [...config.domain.registry.queries.values()].filter(\n query => query.body === undefined && !given.has(query.name),\n )\n if (bodiless.length > 0) {\n throw new Error(\n `RemoteServer.memory: ${bodiless.map(query => `\"${query.name}\"`).join(', ')} ${bodiless.length === 1 ? 'has' : 'have'} no body to run. Declare ${bodiless.length === 1 ? 'it' : 'them'} with Query.define, or give a source in \\`queries\\`.`,\n )\n }\n const queries = [\n ...(config.queries ?? []),\n ...[...config.domain.registry.queries.values()]\n .filter(query => !given.has(query.name))\n .map(query => ({\n ...visible,\n ...RemoteServer.query<P>(query, ({ input, window, principal }) =>\n Effect.flatMap(readableFor(principal), readable =>\n Effect.try({\n try: () => {\n const body = query.body!\n const encoded = Schema.encodeSync(query.Input)(input) as Readonly<\n Record<string, unknown>\n >\n const entity = body.entity.name\n const rows = (store.rows(entity) as ReadonlyArray<Row>).filter(row =>\n readable(entity, row),\n )\n const matched = evaluate(body, encoded, rows)\n // A cursor row that no longer matches still has a place in the\n // order, as a keyset has it: sort it among the matches with the\n // predicates set aside. One that no longer exists has none.\n const locate = (cursor: string) => {\n const row = rows.find(candidate => String(candidate.id) === cursor)\n if (row === undefined) {\n throw new Error(`Cursor \"${cursor}\" names a row that no longer exists`)\n }\n const placed = evaluate({ ...body, where: [] } as typeof body, encoded, [\n ...matched,\n row,\n ])\n return { index: placed.indexOf(row), exact: false }\n }\n const page = pageOf(matched, window, row => String(row.id), locate)\n return {\n edges: page.items.map(row => {\n const id = String(row.id)\n return { entity, id, key: entityKey(entity, id) }\n }),\n start: page.start,\n end: page.end,\n }\n },\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n ),\n ),\n })),\n ]\n\n const server = RemoteServer.make<P>({\n entities: [...entities, ...(config.entities ?? [])],\n queries,\n mutations: config.mutations?.(store) ?? [],\n })\n return {\n ...store,\n server,\n // Typed only where `principal` was given or `P` admits `undefined` (the\n // overloads): otherwise it would answer as nobody, and is not offered.\n layer: Remote.clientLayer(\n RemoteServer.handlers(server, config.principal as P),\n ) as Layer.Layer<RemoteClient>,\n }\n}\n\n/**\n * A Source's refusal as the client receives it: encoded by the mutation's own\n * `Refusal`. A refusal made for another mutation, or one the mutation does not\n * declare, is this side's bug, and says so without the value.\n */\nconst refusalError = (\n Refusal: Schema.Codec<unknown, unknown>,\n mutation: string,\n refused: MutationRefused,\n): Effect.Effect<never, RemoteMutationError> =>\n Effect.gen(function* () {\n const invalid = new RemoteMutationError({ message: 'Invalid mutation refusal' })\n if (refused.mutation !== mutation) return yield* invalid\n const encoded = yield* Schema.encodeUnknownEffect(Refusal)(refused.refusal).pipe(\n Effect.mapError(() => invalid),\n )\n return yield* new RemoteMutationError({ message: refused.message, refusal: encoded })\n })\n\nexport const RemoteServer = {\n /** A backend held in memory, for a first run, a test or a demo. See `memory`. */\n memory,\n\n /** A mutation outcome's report that `ref` now heads the connection. */\n prepend: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'prepend'),\n\n /** A mutation outcome's report that `ref` now ends the connection. */\n append: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'append'),\n\n /** A mutation outcome's report that `ref` left the connection. */\n remove: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'remove'),\n\n /**\n * An entity source. Given the Entity, every member it declares (fields,\n * relations, derived members) may be requested; given anything with a\n * `name` and `fields`, those fields. A request for anything else never\n * reaches `read` or `authorize`. Given only a `name`, every field passes.\n */\n entity: <P = unknown, R = never>(\n entity: EntityName,\n options: {\n readonly read: EntitySource<P, R>['read']\n readonly authorize?: EntitySource<P, R>['authorize']\n readonly filter?: EntitySource<P, R>['filter']\n /** See `EntitySource.shared`: each must be a member the source serves. */\n readonly shared?: ReadonlyArray<string> | undefined\n },\n ): EntitySource<P, R> => {\n const declared = entity.members ?? entity.fields\n const fields = declared === undefined ? undefined : new Set(Object.keys(declared))\n const unserved = (options.shared ?? []).filter(\n field => fields !== undefined && !fields.has(field),\n )\n if (unserved.length > 0) {\n throw new Error(\n `[foldkit-remote-server] ${entity.name}'s shared fields name no member: ${unserved.join(', ')}`,\n )\n }\n return {\n entity: entity.name,\n ...(fields === undefined ? {} : { fields }),\n read: options.read,\n ...(options.authorize === undefined ? {} : { authorize: options.authorize }),\n ...(options.filter === undefined ? {} : { filter: options.filter }),\n ...(options.shared === undefined ? {} : { shared: new Set(options.shared) }),\n }\n },\n\n mutation: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n Refused = unknown,\n >(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n run: (context: {\n readonly input: Input\n readonly principal: P\n /** The client's id for this request, unique within that client only. */\n readonly requestId: string\n /** The operation's identity across clients, for a record of the write; see `MutationSource`. */\n readonly operation: Option.Option<string>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n R\n >,\n ): MutationSource<P, R> => ({\n mutation: mutation.name,\n Input: mutation.Input,\n Output: mutation.Output,\n Refusal: mutation.Refusal,\n run: context =>\n run({\n input: context.input as Input,\n principal: context.principal,\n requestId: context.requestId,\n operation: context.operation,\n }).pipe(\n Effect.map(outcome => ({\n output: outcome.output,\n entities: outcome.entities ?? [],\n connections: outcome.connections ?? [],\n deleted: outcome.deleted ?? [],\n })),\n ),\n }),\n\n /**\n * A refusal of `mutation`, as a value of its declared `Refusal`: fail a\n * Source with it (`yield* RemoteServer.refuse(SavePost, { _tag: 'Field', ... })`)\n * and the client reads it, decoded, with `Data.refusal`. `message` is what a\n * person reads, beside it.\n */\n refuse: <Refused>(\n mutation: MutationDescriptor<string, any, any, Refused>,\n refusal: NoInfer<Refused>,\n message = `Mutation ${mutation.name} was refused`,\n ): MutationRefused => new MutationRefused({ mutation: mutation.name, refusal, message }),\n\n /**\n * A writer's refusal of a row that does not hold the write's `when`: fail\n * `update` or `delete` with it (`yield* RemoteServer.unmet()`), and\n * `RemoteServer.write` answers the mutation's `Unmet` refusal.\n */\n unmet: (message = 'The row does not hold what the write asks of it'): RemoteUnmet =>\n new RemoteUnmet({ message }),\n\n /**\n * A writer's refusal of a row that would break an invariant: fail `update`\n * or `insert` with it, naming the invariant's id and path when the caller\n * may be told them, and `RemoteServer.write` answers the mutation's\n * `Invalid` refusal.\n */\n invalid: (\n message: string,\n rule: Option.Option<string> = Option.none(),\n path: ReadonlyArray<string> = [],\n ): RemoteInvalid => new RemoteInvalid({ message, rule, path }),\n\n /**\n * A refusal of who is asking: fail a Source with it\n * (`yield* RemoteServer.forbid()`) and the write never runs. `reason`, when\n * given, is what the person who asked reads; without it the refusal says\n * nothing of why. `answer` sends it as a 403, and the client's mutation\n * fails with `_tag: 'Forbidden'`.\n */\n forbid: (reason?: string): RemoteForbidden =>\n new RemoteForbidden({\n message: reason ?? 'Forbidden',\n ...(reason === undefined ? {} : { reason }),\n }),\n\n /**\n * A refusal of a caller who could not be told: a `serveFetch` or\n * `defineDocumentHost` resolver fails with it (`RemoteServer.unauthenticated()`)\n * when the credential it was sent no longer holds. It answers 401, with\n * `reason`, when given, for the person who asked.\n */\n unauthenticated: (reason?: string): RemoteUnauthenticated =>\n new RemoteUnauthenticated({\n message: reason ?? 'Unauthenticated',\n ...(reason === undefined ? {} : { reason }),\n }),\n\n /**\n * The Source of a mutation that is a declared `Write`, with no handler: the\n * input bound to the write lands through `writer`, and the row as written\n * answers as a patch (a deletion as `deleted`). An update writes only the\n * keys the client named, when it named some, and fails for a row that is not\n * there; an insert of an id already holding what it writes (a retry)\n * answers with that row, and of one holding anything else fails; a delete of\n * a row already gone succeeds. A row that moved past the revision the write\n * `expect`s is refused as a conflict, and one that does not hold its `when`\n * as unmet; a write with a `when` needs a writer that checks it\n * (`preconditions`), and is refused here without one.\n */\n write: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Refused extends { readonly _tag: 'Conflict' | 'Unmet' | 'Invalid' } = {\n readonly _tag: 'Conflict'\n },\n >(\n mutation: MutationDescriptor<Name, Input, {}, Refused> & {\n readonly write: AnyWrite\n },\n writer: EntityWriter<P, R>,\n ): MutationSource<P, R> => {\n const { write } = mutation\n if (write.input.entity.name !== writer.entity) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" writes ${write.input.entity.name}, but its writer is for ${writer.entity}`,\n )\n }\n // Without a revision, only a ledger tells a retry of an increment from a second one.\n if (write.increments.length > 0 && write.expect === undefined && writer.ledger !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" increments a field and expects no revision, so a retry could add twice; give it \\`expect\\`, or a writer with a ledger`,\n )\n }\n if (write.increments.length > 0 && writer.increments !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" increments a field, but its writer for ${writer.entity} does not add one (increments)`,\n )\n }\n // An update judges every invariant; an insert, with no row before, the state ones alone.\n const judged = Entity.invariants(write.input.entity).filter(\n held => write._tag === 'Update' || !Entity.readsBefore(held),\n )\n if (judged.length > 0 && writer.invariants !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" writes ${writer.entity}, which has invariants, but its writer does not judge them (invariants)`,\n )\n }\n // An insert's row is its values: a field it leaves to a default the writer cannot judge.\n if (write._tag === 'Insert') {\n const sets = new Set(['id', ...write.sets.map(set => set.field.key)])\n const unset = judged.flatMap(held =>\n held.after.filter(key => !sets.has(key)).map(key => `${held.id} reads ${key}`),\n )\n if (unset.length > 0) {\n throw new Error(\n `[foldkit-remote-server] insert \"${mutation.name}\" leaves unset a field an invariant reads (${unset.join('; ')})`,\n )\n }\n }\n if (Option.isSome(write.when) && writer.preconditions !== true) {\n throw new Error(\n `[foldkit-remote-server] write \"${mutation.name}\" has a precondition, but its writer for ${writer.entity} does not check one (preconditions)`,\n )\n }\n const encodeInput = Schema.encodeUnknownEffect(\n write.input.schema as unknown as Schema.Codec<unknown, Readonly<Record<string, unknown>>>,\n )\n return {\n mutation: mutation.name,\n writes: { entity: writer.entity, writer, write },\n Input: mutation.Input,\n Output: mutation.Output,\n Refusal: mutation.Refusal,\n run: ({ input, principal, keys, operation }) => {\n const given = input as never\n const expect = Write.expected(write, given)\n const conflict = (bound: { readonly entity: string; readonly id: string }) =>\n RemoteServer.refuse(\n mutation,\n { _tag: 'Conflict' } as Refused,\n `${bound.entity} ${bound.id} changed since it was read`,\n )\n // The body reads the input as a query's does: encoded, by its keys.\n const when = Option.match(write.when, {\n onNone: () => Effect.succeed(Option.none<WriteWhen>()),\n onSome: body =>\n encodeInput(given).pipe(\n Effect.map(encoded => Option.some({ body, input: encoded })),\n Effect.mapError(\n () => new RemoteServerError({ message: `${mutation.name}'s input did not encode` }),\n ),\n ),\n })\n const unmet = <A>(\n bound: { readonly entity: string; readonly id: string },\n writing: Effect.Effect<\n A,\n RemoteServerError | RemoteForbidden | RemoteUnmet | RemoteInvalid,\n R\n >,\n ) =>\n Effect.catchTag(\n writing,\n 'RemoteUnmet',\n (): Effect.Effect<never, RemoteServerError | MutationRefused> =>\n Option.isNone(write.when)\n ? // A writer unmet with no precondition to meet is wrong, and the\n // mutation declares no such refusal: the server's error, not one.\n Effect.fail(\n new RemoteServerError({\n message: `${writer.entity}'s writer refused ${mutation.name}, which has no precondition, as unmet`,\n }),\n )\n : Effect.fail(\n RemoteServer.refuse(\n mutation,\n { _tag: 'Unmet' } as Refused,\n `${bound.entity} ${bound.id} does not hold what ${mutation.name} asks of it`,\n ),\n ),\n )\n // The writer judged the row it would leave; the client is told what the writer said.\n const invalid = <A>(\n writing: Effect.Effect<\n A,\n RemoteServerError | RemoteForbidden | MutationRefused | RemoteInvalid,\n R\n >,\n ) =>\n Effect.catchTag(writing, 'RemoteInvalid', refused =>\n Effect.fail(\n RemoteServer.refuse(\n mutation,\n {\n _tag: 'Invalid',\n rule: refused.rule,\n message: refused.message,\n path: refused.path,\n } as unknown as Refused,\n refused.message,\n ),\n ),\n )\n const answered = (bound: BoundWrite, values: Readonly<Record<string, unknown>>) => {\n const read = writer.read\n const shown =\n read === undefined\n ? Effect.succeed(Option.some(values))\n : read({ id: bound.id, fields: Object.keys(values), principal })\n return Effect.map(\n shown,\n Option.match({\n onNone: () => ({\n output: {},\n entities: [],\n connections: [],\n deleted: [{ entity: bound.entity, id: bound.id }],\n }),\n onSome: seen => ({\n output: {},\n entities: [{ entity: bound.entity, id: bound.id, values: seen }],\n connections: [],\n deleted: [],\n }),\n }),\n )\n }\n return Match.value(write).pipe(\n Match.tagsExhaustive({\n Update: () =>\n Effect.gen(function* () {\n const bound = Write.bind(write, given, keys)\n if (\n write.increments.length > 0 &&\n write.expect === undefined &&\n Option.isNone(operation)\n ) {\n // The ledger keys a write by its operation: with none, a retry could add twice.\n return yield* new RemoteServerError({\n message: `${mutation.name} increments a field with no revision, so it needs an operation id`,\n })\n }\n const written = yield* invalid(\n unmet(\n bound,\n writer.update({\n id: bound.id,\n operation,\n values: bound.values,\n increments: bound.increments,\n links: bound.links,\n expect,\n when: yield* when,\n principal,\n }),\n ),\n )\n if (Option.isSome(written)) return yield* answered(bound, written.value)\n return yield* Option.isSome(expect)\n ? Effect.fail(conflict(bound))\n : Effect.fail(\n new RemoteServerError({\n message: `No ${bound.entity} ${bound.id} to update`,\n }),\n )\n }),\n // Written whole: there is no row a client could have changed some keys of.\n Insert: () =>\n Effect.gen(function* () {\n const bound = Write.bind(write, given)\n const row = yield* invalid(\n writer.insert({\n id: bound.id,\n values: bound.values,\n links: bound.links,\n principal,\n }),\n )\n return yield* answered(bound, row)\n }),\n Delete: () =>\n Effect.gen(function* () {\n const bound = Write.bind(write, given)\n const outcome = yield* invalid(\n unmet(\n bound,\n writer.delete({ id: bound.id, expect, when: yield* when, principal }),\n ),\n )\n // Gone already is gone: only a revision the row moved past refuses.\n if (outcome === 'moved') return yield* Effect.fail(conflict(bound))\n return {\n output: {},\n entities: [],\n connections: [],\n deleted: [{ entity: bound.entity, id: bound.id }],\n }\n }),\n }),\n )\n },\n }\n },\n\n query: <P = unknown, R = never, Input = unknown>(\n query: QueryDescriptor<string, Input, unknown>,\n run: (context: {\n readonly input: Input\n readonly window: QueryWindow\n readonly principal: P\n readonly select?: RelationRequirement | undefined\n }) => Effect.Effect<QueryPage, RemoteServerError, R>,\n ): QuerySource<P, R> => ({\n query: query.name,\n Input: query.Input,\n run: context =>\n run({\n input: context.input as Input,\n window: context.window,\n principal: context.principal,\n ...(context.select === undefined ? {} : { select: context.select }),\n }),\n }),\n\n /** Streams live entity patches for a client's live requirements. */\n live: <P = unknown, R = never>(\n entity: EntityName,\n options: { readonly subscribe: LiveSource<P, R>['subscribe'] },\n ): LiveSource<P, R> => ({\n entity: entity.name,\n subscribe: options.subscribe,\n }),\n\n /**\n * A `LiveHub` over entity sources. Pass it to `handlers` as `live`, and every\n * mutation's answered patches and deletions are published to it; call\n * `hub.changed(ref, fields)` yourself only for a write that is not a\n * mutation (a database trigger, a job). Each subscriber that selects any of\n * those fields receives them, re-read through the entity source under its\n * own principal.\n */\n liveHub,\n\n make: <P = unknown, R = never>(config: {\n readonly entities: readonly EntitySource<P, R>[]\n readonly mutations?: readonly MutationSource<P, R>[]\n readonly queries?: readonly QuerySource<P, R>[]\n readonly live?: readonly LiveSource<P, R>[]\n }): ServerDefinition<P, R> => ({\n entities: new Map(config.entities.map(source => [source.entity, source])),\n mutations: new Map((config.mutations ?? []).map(source => [source.mutation, source])),\n queries: new Map((config.queries ?? []).map(source => [source.query, source])),\n live: new Map((config.live ?? []).map(source => [source.entity, source])),\n }),\n\n /**\n * Checks every source name against the declared domain, so an undeclared\n * entity/query/mutation fails at startup rather than returning nothing at\n * call time.\n */\n validate: (domain: RemoteDescriptor, server: ServerDefinition<any, any>): void => {\n const assertDeclared = (\n kind: string,\n declared: ReadonlyMap<string, unknown>,\n names: Iterable<string>,\n ): void => {\n for (const name of names) {\n if (!declared.has(name))\n throw new Error(`RemoteServer: ${kind} \"${name}\" is not declared in the Remote domain`)\n }\n }\n assertDeclared('entity', domain.registry.entities, server.entities.keys())\n assertDeclared('query', domain.registry.queries, server.queries.keys())\n assertDeclared('mutation', domain.registry.mutations, server.mutations.keys())\n },\n\n /**\n * Reads entity requirements through the entity sources, level by level,\n * following relations as `FoldkitRemoteRead` does. Shared by the read\n * handler and the query handler's payload: a query page's items are just\n * requirements the page names, so one response carries both.\n */\n readHelper: <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R>,\n requests: ReadonlyArray<Requirement>,\n ): Effect.Effect<\n {\n readonly entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }>\n readonly settled: Array<{\n readonly entity: string\n readonly id: string\n readonly fields: Array<string>\n }>\n },\n RemoteReadError,\n R\n > =>\n Effect.gen(function* () {\n const entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }> = []\n const settled = new Map<string, { entity: string; id: string; fields: Set<string> }>()\n const settle = (entity: string, id: string, fields: ReadonlyArray<string>): void => {\n if (fields.length === 0) return\n const key = `${entity}:${id}`\n const entry = settled.get(key) ?? { entity, id, fields: new Set<string>() }\n for (const field of fields) entry.fields.add(field)\n settled.set(key, entry)\n }\n const fetched = new Map<string, Set<string>>()\n const fetchedValues = new Map<string, Record<string, unknown>>()\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH\n const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY)\n\n const over = checkIdsPerEntity(requests, maxIds)\n if (over !== undefined) {\n return yield* new RemoteReadError({ message: `Too many \"${over}\" ids in one read batch` })\n }\n const paged = checkPagesPerRelation(requests)\n if (paged !== undefined) {\n return yield* new RemoteReadError({ message: `Too many pages of \"${paged}\" in one read` })\n }\n\n let pending: ReadonlyArray<Requirement> = requests\n for (let depth = 0; pending.length > 0; depth++) {\n if (depth > maxDepth) {\n return yield* new RemoteReadError({\n message: `Nested selection deeper than ${maxDepth} relation levels`,\n })\n }\n const next: Requirement[] = []\n\n const follow = (\n values: Record<string, unknown>,\n relations: Readonly<Record<string, RelationRequirement>>,\n ): void => {\n for (const [field, relation] of Object.entries(relations)) {\n if (!Object.hasOwn(values, field)) continue\n for (const ref of refsIn(values[field])) {\n if (ref.entity !== relation.entity) continue\n const key = `${relation.entity}:${ref.id}`\n const read = fetched.get(key)\n const fields = relation.fields.filter(name => read?.has(name) !== true)\n if (fields.length > 0) {\n next.push({\n entity: relation.entity,\n id: ref.id,\n fields,\n ...(relation.windows === undefined ? {} : { windows: relation.windows }),\n ...(relation.relations === undefined ? {} : { relations: relation.relations }),\n })\n } else if (relation.relations !== undefined) {\n follow(fetchedValues.get(key) ?? {}, relation.relations)\n }\n }\n }\n }\n\n for (const { ids, slice, renames } of groupByEntity(pending)) {\n const name = slice.entity\n const source = server.entities.get(name)\n if (source === undefined) continue\n const allowed = allowedFields(source, principal, slice.fields)\n const allowedSet = new Set(allowed)\n const idList = [...ids.keys()]\n for (const [id, asked] of ids) {\n settle(\n name,\n id,\n [...asked]\n .filter(field => !allowedSet.has(field))\n .map(field => renamed(renames, field)),\n )\n }\n if (allowed.length === 0) continue\n\n const windows = windowsOf(slice.windows, allowed)\n const records = yield* readFiltered(source, principal, allowed, fields =>\n Effect.map(\n Effect.forEach(\n Array.from({ length: Math.ceil(idList.length / maxIds) }, (_, chunk) =>\n idList.slice(chunk * maxIds, (chunk + 1) * maxIds),\n ),\n chunk => source.read({ ids: chunk, fields, principal, ...windows }),\n ),\n chunks => chunks.flat(),\n ),\n ).pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n )\n\n for (const record of records) {\n const values: Record<string, unknown> = Object.create(null)\n const omitted: string[] = []\n const asked = ids.get(record.id)\n for (const field of allowed) {\n if (Object.hasOwn(record.values, field))\n values[renamed(renames, field)] = record.values[field]\n else if (asked?.has(field) === true) omitted.push(renamed(renames, field))\n }\n entities.push({ entity: name, id: record.id, values })\n settle(name, record.id, omitted)\n\n const key = `${name}:${record.id}`\n const known = fetched.get(key) ?? new Set<string>()\n for (const field of allowed) known.add(renamed(renames, field))\n fetched.set(key, known)\n fetchedValues.set(key, { ...fetchedValues.get(key), ...values })\n\n follow(values, slice.relations ?? {})\n }\n }\n pending = next.flatMap(request => {\n const read = fetched.get(`${request.entity}:${request.id}`)\n const fields = request.fields.filter(field => read?.has(field) !== true)\n return fields.length === 0 ? [] : [{ ...request, fields }]\n })\n }\n\n return {\n entities,\n settled: [...settled.values()].map(entry => ({ ...entry, fields: [...entry.fields] })),\n }\n }),\n\n /**\n * Answers one JSON request through `handlers`: what an HTTP endpoint, a\n * worker or a server in the page calls with the body it received, parsed.\n * The request and its payload are decoded by the protocol's own schemas\n * before a handler sees them, so an operation name is one of Remote's three\n * and nothing else. A body that is not a request is a 400; a caller who\n * could not be told a 401; a refusal of who is asking a 403; a handler's\n * failure a 500 with its message; a defect a 500 that says nothing of it.\n * `Remote.json` and `Remote.http` are the other end.\n */\n answer: <R>(\n handlers: RemoteRpcClient<R>,\n body: unknown,\n ): Effect.Effect<\n { readonly status: 200 | 400 | 401 | 403 | 422 | 500; readonly body: RemoteJsonAnswer },\n never,\n R\n > => {\n const asked = {\n read: (payload: unknown) =>\n Effect.flatMap(Schema.decodeUnknownEffect(ReadBatch)(payload), handlers.FoldkitRemoteRead),\n query: (payload: unknown) =>\n Effect.flatMap(\n Schema.decodeUnknownEffect(QueryRequest)(payload),\n handlers.FoldkitRemoteQuery,\n ),\n mutate: (payload: unknown) =>\n Effect.flatMap(\n Schema.decodeUnknownEffect(MutationRequest)(payload),\n handlers.FoldkitRemoteMutate,\n ),\n }\n return Schema.decodeUnknownEffect(RemoteJsonRequest)(body).pipe(\n Effect.flatMap(({ operation, payload }): Effect.Effect<unknown, AnswerError, R> =>\n asked[operation](payload),\n ),\n Effect.map(result => ({ status: 200 as const, body: { result } })),\n Effect.catchTag('SchemaError', error =>\n Effect.succeed({ status: 400 as const, body: { error: error.message } }),\n ),\n Effect.catchTag('Unauthenticated', error => Effect.succeed(unauthenticatedAnswer(error))),\n Effect.catchTag('Forbidden', error =>\n Effect.succeed({\n status: 403 as const,\n body: {\n error: error.message,\n forbidden: error.reason === undefined ? {} : { reason: error.reason },\n },\n }),\n ),\n // A refusal is the mutation's answer, not a failure of the server.\n Effect.catchTag('RemoteMutationError', error =>\n Effect.succeed(\n error.refusal === undefined\n ? { status: 500 as const, body: { error: error.message } }\n : { status: 422 as const, body: { error: error.message, refusal: error.refusal } },\n ),\n ),\n Effect.catch(error =>\n Effect.succeed({ status: 500 as const, body: { error: error.message } }),\n ),\n // A defect is a bug on this side: the caller learns there was one, not what.\n Effect.catchCause(() =>\n Effect.succeed({ status: 500 as const, body: { error: 'Internal error' } }),\n ),\n )\n },\n\n /**\n * Compiles the server into Remote's RPC handlers, answering as `principal`:\n * a value, or a Context key (`G.Principal`) read on each call, which\n * authentication provides per request. Unknown entities, entities with no\n * allowed fields, and unknown mutations return an error or nothing rather\n * than leaking existence.\n */\n handlers: <P, R, I = never>(\n server: ServerDefinition<P, R>,\n principal: P | Context.Key<I, P>,\n options: HandlerOptions<P, R> = {},\n ): RemoteRpcClient<R | I> => {\n // A Context key is read on each call, so one handler set answers every request.\n const asking: Effect.Effect<P, never, I> = Context.isKey(principal)\n ? principal\n : Effect.succeed(principal)\n return {\n FoldkitRemoteRead: Effect.fn('RemoteServer.FoldkitRemoteRead')(function* (payload) {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return yield* mismatch\n const caller = yield* asking\n return yield* RemoteServer.readHelper(server, caller, options, payload.requests)\n }),\n\n FoldkitRemoteMutate: Effect.fn('RemoteServer.FoldkitRemoteMutate')(function* (payload) {\n const source = server.mutations.get(payload.mutation)\n if (source === undefined) {\n return yield* new RemoteMutationError({\n message: `Unknown mutation: ${payload.mutation}`,\n })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation input' })),\n ),\n )\n\n const caller = yield* asking\n const outcome = yield* source\n .run({\n input,\n principal: caller,\n requestId: payload.requestId,\n operation: Option.fromUndefinedOr(payload.operation),\n keys: payload.keys,\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n Effect.catchTag('MutationRefused', refused =>\n refusalError(source.Refusal, payload.mutation, refused),\n ),\n )\n\n const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation output' })),\n ),\n )\n\n // What the mutation answers is what changed, so live subscribers hear it\n // without the handler naming it again. The write has committed by now: a\n // failed publish is logged, never the mutation's failure, which a client\n // would retry.\n const hub = options.live\n if (hub !== undefined) {\n // A declared write's answer is the row as stored; a handler's is its own claim.\n const stored = source.writes !== undefined\n yield* Effect.forEach(outcome.entities, patch =>\n hub.changed(\n { entity: patch.entity, id: patch.id },\n Object.keys(patch.values),\n stored ? patch.values : undefined,\n ),\n ).pipe(\n Effect.andThen(Effect.forEach(outcome.deleted, gone => hub.deleted(gone))),\n Effect.catchCause(cause =>\n Effect.logWarning(\n 'RemoteServer: a mutation committed but its live publish failed',\n cause,\n ),\n ),\n )\n }\n\n return {\n output,\n entities: outcome.entities.map(patch => ({\n entity: patch.entity,\n id: patch.id,\n values: patch.values,\n })),\n connections: outcome.connections,\n deleted: outcome.deleted.map(gone => ({ entity: gone.entity, id: gone.id })),\n }\n }),\n\n FoldkitRemoteQuery: Effect.fn('RemoteServer.FoldkitRemoteQuery')(function* (payload) {\n const source = server.queries.get(payload.query)\n if (source === undefined) {\n return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteQueryError({ message: 'Invalid query input' })),\n ),\n )\n\n const select = payload.select\n if (select !== undefined) {\n const paged = checkPagesPerRelation([select])\n if (paged !== undefined) {\n return yield* new RemoteQueryError({\n message: `Too many pages of \"${paged}\" in one query select`,\n })\n }\n }\n\n const caller = yield* asking\n const page = yield* source\n .run({\n input,\n window: payload.window,\n principal: caller,\n ...(select === undefined ? {} : { select }),\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n\n if (select === undefined) return { edges: page.edges, start: page.start, end: page.end }\n // The page's items as requirements, so the selected fields ride back\n // with the edges in one response. Edges of another entity (a query\n // lists one) take no fields: the client's planner asks for them next.\n const requirements: Requirement[] = page.edges.flatMap(edge =>\n edge.entity === select.entity\n ? [\n {\n entity: select.entity,\n id: edge.id,\n fields: [...select.fields],\n ...(select.windows === undefined ? {} : { windows: select.windows }),\n ...(select.relations === undefined ? {} : { relations: select.relations }),\n },\n ]\n : [],\n )\n if (requirements.length === 0)\n return { edges: page.edges, start: page.start, end: page.end, entities: [], settled: [] }\n const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(\n Effect.catchTag('RemoteReadError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n return { edges: page.edges, start: page.start, end: page.end, ...read }\n }),\n\n FoldkitRemoteLive: payload => {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return Stream.fail(mismatch)\n return Stream.unwrap(\n Effect.map(asking, caller => {\n const entities = [...new Set(payload.requirements.map(request => request.entity))]\n const streams: Array<Stream.Stream<LiveChangeValue, RemoteServerError, R>> =\n entities.flatMap(entity => {\n const source = server.live.get(entity)\n if (source === undefined) return []\n return [\n source.subscribe({\n requirements: payload.requirements.filter(request => request.entity === entity),\n after: payload.after,\n principal: caller,\n }),\n ]\n })\n if (options.live !== undefined) {\n streams.push(\n options.live.subscribe({\n requirements: payload.requirements,\n after: payload.after,\n principal: caller,\n maxIdsPerEntity: options.maxIdsPerEntity,\n }),\n )\n }\n // An entity with no live source simply contributes nothing; the client's\n // planner refetches it rather than the stream failing.\n return Stream.mergeAll(streams, { concurrency: 'unbounded' }).pipe(\n Stream.mapError(error => new RemoteLiveError({ message: error.message })),\n )\n }),\n )\n },\n }\n },\n}\n\nexport * from './evaluate.js'\n"],"mappings":";;;;;AAGA,MAAa,yBAAyB,aACnC;CACC,QAAQ;CACR,MAAM;EACJ,OAAO,QAAQ;EACf,iBAAiB,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CAChF;AACF;;;;;;;;;;ACyDF,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;;;;;;AAOH,IAAa,cAAb,cAAiC,OAAO,YAAyB,CAAC,CAAC,eAAe,EAChF,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQJ,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB;CACtF,SAAS,OAAO;CAChB,MAAM,OAAO,OAAO,OAAO,MAAM;CACjC,MAAM,OAAO,MAAM,OAAO,MAAM;AAClC,CAAC,CAAC,CAAC,CAAC;;;;;;AAaJ,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CAAC,mBAAmB;;CAE5F,UAAU,OAAO;CACjB,SAAS,OAAO;;CAEhB,SAAS,OAAO;AAClB,CAAC,CAAC,CAAC,CAAC;;AA2DJ,MAAM,gBACJ,QACA,WACA,QACA,SAIA,OAAO,WAAW,KAAA,IACd,KAAK,MAAM,IACX,OAAO,QAAQ,OAAO,OAAO,WAAW,MAAM,IAAG,SAC/C,OAAO,IAAI,KAAK,KAAK,MAAM,IAAG,YAAW,QAAQ,IAAI,KAAK,KAAK,CAAC,CAClE;AA6HN,MAAM,oBACJ,YACA,KACA,aACqB;CACrB,MAAM,OAAO;EAAE,QAAQ,IAAI;EAAQ,IAAI,IA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