foldkit-remote-server 0.10.0 → 0.12.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 CHANGED
@@ -32,7 +32,8 @@ Remote client -> Message -> Data.reduce -> Model
32
32
 
33
33
  A Source is deliberately small: it says how your application reads one Entity,
34
34
  runs one Query or Mutation, or produces one live stream. The package does **not**
35
- own HTTP, WebSockets, authentication, or a database connection. Authentication
35
+ own HTTP, WebSockets, authentication, or a database connection;
36
+ [`answer`](#over-plain-json) answers a JSON request a server you run received. Authentication
36
37
  resolves a `principal` outside this package; database/API clients remain Effect
37
38
  requirements of the Sources that use them.
38
39
 
@@ -211,7 +212,12 @@ RemoteServer.entity(entity, {
211
212
 
212
213
  Important consequences:
213
214
 
214
- - a field the Entity does not declare never reaches `authorize` or `read`;
215
+ - a field the Entity does not declare never reaches `authorize` or `read`.
216
+ Its fields, relations and derived members are all declared, so a relation
217
+ such as `owner` is read and followed like any field;
218
+ - a requested field is client input, answered only when the source returns it
219
+ as its own: `constructor` or `__proto__` is settled, never read off
220
+ `Object.prototype`;
215
221
  - `authorize` can only remove requested fields, never add new ones;
216
222
  - a Source may return a partial entity — a requested field it omits is settled,
217
223
  so the client records it unavailable rather than asking again;
@@ -341,15 +347,22 @@ is *unknown* in SQL and matches no row, where JavaScript would call the two
341
347
  equal. A comparison keeps a row only when it is true, so a null on either side
342
348
  drops it.
343
349
 
344
- Two things it refuses rather than guesses:
350
+ What it refuses rather than guesses:
345
351
 
346
352
  - **Ordering by a column that is null in some row.** SQLite sorts nulls first,
347
353
  Postgres sorts them last for `asc`: the databases disagree with each other, so
348
354
  there is no answer to be conformant to and picking one would make this wrong
349
355
  against the other.
350
356
  - **Comparing values it has no order for**, such as a number against a string.
357
+ - **Searching text that holds a NUL character**, which Postgres text cannot
358
+ hold and SQLite's `like` stops at.
351
359
 
352
- Both throw where the query runs, naming the query and the field.
360
+ Each throws where the query runs, naming the query. An ordering is checked
361
+ before anything is sorted: every term over every matched row, in row order, so
362
+ the error names the first row that breaks it (`number and string` when a later
363
+ row holds text), the same on every engine, whichever pair a sort would have
364
+ compared first. One matched row, or none, has nothing to order and is never
365
+ refused.
353
366
 
354
367
  ### Checking an interpreter against the semantics
355
368
 
@@ -630,6 +643,14 @@ const backend = RemoteServer.memory({
630
643
  backend.layer // provide it where the real RemoteClient would go
631
644
  ```
632
645
 
646
+ `backend.server` is the server definition the layer answers through. Serve
647
+ it over a real transport to try a client against HTTP, or to test another
648
+ server against it:
649
+
650
+ ```ts
651
+ const served = RemoteRpc.toLayer(RemoteServer.handlers(backend.server, undefined))
652
+ ```
653
+
633
654
  - Rows are in their **wire shape**: a relation is its ref key (`'User:u1'`),
634
655
  and a to-many relation is a list of them.
635
656
  - A query declared with `Query.define` is answered by running its body over
@@ -637,8 +658,81 @@ backend.layer // provide it where the real RemoteClient would go
637
658
  the reference interpreter, and paged with offset cursors. A query with no
638
659
  body has nothing to run and is refused when the backend is made, unless you
639
660
  pass a source for it in `queries`.
640
- - It pushes no live changes and authorizes nothing: every field is readable.
641
- It is not a server to deploy.
661
+ - Every field is readable unless `authorize` names the entity; see below. It
662
+ pushes no live changes, and it is not a server to deploy.
663
+
664
+ To try authorization without a database, give `authorize` per entity name,
665
+ the function `RemoteServer.entity` takes, and the `principal` the layer
666
+ answers as. The principal's type is inferred from them, as `RemoteServer.make`
667
+ infers it from its sources:
668
+
669
+ ```ts
670
+ const guarded = RemoteServer.memory({
671
+ domain: Data,
672
+ rows: { Project: [{ id: 'p1', name: 'Apollo', privateNotes: 'Internal' }] },
673
+ principal: { isAdmin: false },
674
+ authorize: {
675
+ Project: (principal: Principal, fields) =>
676
+ fields.filter(field => field !== 'privateNotes' || principal.isAdmin),
677
+ },
678
+ })
679
+
680
+ // The layer reads as a non-admin; the server answers as anyone.
681
+ const asAdmin = RemoteServer.handlers(guarded.server, { isAdmin: true })
682
+ ```
683
+
684
+ A withheld field is settled, as from any server: the client stops asking for
685
+ it, and a selection that needs it fails as `Unavailable`. A name in
686
+ `authorize` the domain does not declare is refused when the backend is made.
687
+
688
+ ## Over a MessagePort
689
+
690
+ `servePort(handlers, port)` from `foldkit-remote-server/port` answers
691
+ `foldkit-remote/port`'s client over one `MessagePort`, for a server in a
692
+ worker or in the page. It speaks Effect's RPC worker protocol, so reads,
693
+ queries, mutations and live streams cross it with their typed errors, and an
694
+ interrupted call interrupts its handler. It returns once the client closes its
695
+ end; interrupt it to stop sooner:
696
+
697
+ ```ts
698
+ import { servePort } from 'foldkit-remote-server/port'
699
+
700
+ // In the host, for each port a page hands it; `handlers` as above.
701
+ Effect.runFork(servePort(handlers, port))
702
+ ```
703
+
704
+ It binds no principal: pass the `handlers` for the conversation's own, as
705
+ everywhere else. It needs no browser package: the port is driven through
706
+ `effect/workers` directly.
707
+
708
+ ## Over plain JSON
709
+
710
+ `RemoteServer.answer(handlers, body)` answers one request as `Remote.http`
711
+ and `Remote.json` send it, whatever received it: an HTTP route, a worker, a
712
+ server running in the page. It decodes the request and its payload by the
713
+ protocol's own schemas before a handler sees them, so an operation is one of
714
+ Remote's three and nothing else, and says what to send:
715
+
716
+ ```ts
717
+ // A fetch-style route (Bun, Deno, a Worker; Node through its own adapter).
718
+ const route = async (request: Request): Promise<Response> => {
719
+ const body: unknown = await request.json().catch(() => null)
720
+ const answered = await Effect.runPromise(RemoteServer.answer(handlers, body))
721
+ return Response.json(answered.body, { status: answered.status })
722
+ }
723
+ ```
724
+
725
+ - **200** with `{ result }`: the handler answered.
726
+ - **400** with `{ error }`: the body is not a request, names an operation
727
+ Remote does not have, or its payload fails the protocol's schema. No
728
+ handler ran.
729
+ - **500** with `{ error }`: the handler failed, and the message is its own;
730
+ or something on this side broke, and the message is `Internal error`,
731
+ nothing more.
732
+
733
+ It binds no principal: pass the `handlers` for the request's own,
734
+ established by your authentication, as everywhere else. It carries no live
735
+ data.
642
736
 
643
737
  ## What it does not own
644
738
 
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Effect, Layer, Schema, Stream } from "effect";
2
2
  import { QueryEvaluateError, Row, assertSupported, evaluate, supported } from "foldkit-entity";
3
- import { Boundary, ConnectionChangeSchema, ConnectionIdentity, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RelationRequirement, RemoteClient, RemoteDescriptor, RemoteReadError, RemoteRpcClient, Requirement } from "foldkit-remote";
3
+ import { Boundary, ConnectionChangeSchema, ConnectionIdentity, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RelationRequirement, RemoteClient, RemoteDescriptor, RemoteJsonAnswer, RemoteReadError, RemoteRpcClient, Requirement } from "foldkit-remote";
4
4
  //#region src/index.d.ts
5
5
  declare const RemoteServerError_base: Schema.Class<RemoteServerError, Schema.TaggedStruct<"RemoteServerError", {
6
6
  readonly message: Schema.String;
@@ -133,10 +133,15 @@ export interface LiveHub<P, R = never> {
133
133
  /** How many subscribers are registered now. */
134
134
  readonly size: Effect.Effect<number>;
135
135
  }
136
- /** A descriptor's name and, when it declares them, its fields. */
136
+ /**
137
+ * A descriptor's name and, when it declares them, its readable members: an
138
+ * Entity's `members` (its fields, relations and derived members), or a plain
139
+ * descriptor's `fields`.
140
+ */
137
141
  interface EntityName {
138
142
  readonly name: string;
139
143
  readonly fields?: Readonly<Record<string, unknown>> | undefined;
144
+ readonly members?: Readonly<Record<string, unknown>> | undefined;
140
145
  }
141
146
  /** One entity's rows in their wire shape: a relation is its ref key, `'User:u1'`. */
142
147
  export type MemoryRows = Readonly<Record<string, ReadonlyArray<Readonly<Record<string, unknown>> & {
@@ -153,18 +158,36 @@ export interface MemoryStore {
153
158
  readonly write: (entity: string, id: string, values: Readonly<Record<string, unknown>>) => void;
154
159
  readonly remove: (entity: string, id: string) => void;
155
160
  }
156
- export interface MemoryBackend extends MemoryStore {
157
- /** A `RemoteClient` answering from the rows. Provide it where the real one would go. */
161
+ export interface MemoryBackend<P = undefined> extends MemoryStore {
162
+ /**
163
+ * A `RemoteClient` answering from the rows as the configured `principal`.
164
+ * Provide it where the real one would go.
165
+ */
158
166
  readonly layer: Layer.Layer<RemoteClient>;
167
+ /**
168
+ * The server the layer answers through, for serving the rows over a real
169
+ * transport, or as another principal:
170
+ * `RemoteRpc.toLayer(RemoteServer.handlers(backend.server, principal))`.
171
+ */
172
+ readonly server: ServerDefinition<P>;
159
173
  }
174
+ /** What `RemoteServer.memory` is made from. See `memory`. */
175
+ export type MemoryConfig<P> = {
176
+ readonly domain: Pick<RemoteDescriptor, 'registry'>;
177
+ readonly rows: MemoryRows;
178
+ readonly queries?: ReadonlyArray<QuerySource<P>>;
179
+ readonly mutations?: (store: MemoryStore) => ReadonlyArray<MutationSource<P>>;
180
+ /** Per entity name, the fields a principal may read, as `RemoteServer.entity` takes it. */
181
+ readonly authorize?: Readonly<Record<string, NonNullable<EntitySource<P>['authorize']>>>;
182
+ } & (undefined extends P ? {
183
+ readonly principal?: P;
184
+ } : {
185
+ /** Who the `layer` answers as. */
186
+ readonly principal: P;
187
+ });
160
188
  export declare const RemoteServer: {
161
189
  /** A backend held in memory, for a first run, a test or a demo. See `memory`. */
162
- memory: (config: {
163
- readonly domain: Pick<RemoteDescriptor, "registry">;
164
- readonly rows: MemoryRows;
165
- readonly queries?: ReadonlyArray<QuerySource<undefined>>;
166
- readonly mutations?: (store: MemoryStore) => ReadonlyArray<MutationSource<undefined>>;
167
- }) => MemoryBackend;
190
+ memory: <P = undefined>(config: MemoryConfig<P>) => MemoryBackend<P>;
168
191
  /** A mutation outcome's report that `ref` now heads the connection. */
169
192
  prepend: (connection: ConnectionIdentity, ref: {
170
193
  readonly entity: string;
@@ -181,9 +204,10 @@ export declare const RemoteServer: {
181
204
  readonly id: string;
182
205
  }) => ConnectionChange;
183
206
  /**
184
- * An entity source. Given the Entity (or anything with its `name` and
185
- * `fields`), a request for a field the entity does not declare never
186
- * reaches `read` or `authorize`.
207
+ * An entity source. Given the Entity, every member it declares (fields,
208
+ * relations, derived members) may be requested; given anything with a
209
+ * `name` and `fields`, those fields. A request for anything else never
210
+ * reaches `read` or `authorize`. Given only a `name`, every field passes.
187
211
  */
188
212
  entity: <P = unknown, R = never>(entity: EntityName, options: {
189
213
  readonly read: EntitySource<P, R>["read"];
@@ -248,6 +272,19 @@ export declare const RemoteServer: {
248
272
  readonly fields: Array<string>;
249
273
  }>;
250
274
  }, RemoteReadError, R>;
275
+ /**
276
+ * Answers one JSON request through `handlers`: what an HTTP endpoint, a
277
+ * worker or a server in the page calls with the body it received, parsed.
278
+ * The request and its payload are decoded by the protocol's own schemas
279
+ * before a handler sees them, so an operation name is one of Remote's three
280
+ * and nothing else. A body that is not a request is a 400; a handler's
281
+ * failure a 500 with its message; a defect a 500 that says nothing of it.
282
+ * `Remote.json` and `Remote.http` are the other end.
283
+ */
284
+ answer: <R>(handlers: RemoteRpcClient<R>, body: unknown) => Effect.Effect<{
285
+ readonly status: 200 | 400 | 500;
286
+ readonly body: RemoteJsonAnswer;
287
+ }, never, R>;
251
288
  handlers: <P, R>(server: ServerDefinition<P, R>, principal: P, options?: HandlerOptions<P, R>) => RemoteRpcClient<R>;
252
289
  };
253
290
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;qBAsCa,0BAA0B;iBAOtB;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;;;YAI1B,mBAAmB,OAAO,OAAO,YAAY;iBA8CxC,gBAAgB;WACtB,QAAQ;WACR,WAAW,cAAc;;WAEzB,cAAc,cAAc;;;;;WAK5B,UAAU;aAAyB;aAAyB;;;iBAGtD,eAAe,GAAG;WACxB;WACA,OAAO,OAAO;WACd,QAAQ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,iBAAK,OAC5B,wBAAwB,iBAAe,MACxC;aACK,OAAO;aACP,QAAQ;aACR,WAAW;aACX,SAAS;QACd,OAAO,OAAO,WAAW,mBAAmB,OACjD,YAAY,GAAG;;EAaX,OAAA,aAAa,WAAC,QACX,YAAU;aACE,WAAW,WAAW,GAAG;QAC5C,WAAW,GAAG;;;;;;;;;EA/pBF,UAAA,GAAG,GAAC,UAAY,cAAc,aAAa,GAAG,QAAM,OAAO,OAAO,QAAQ,GAAG;EA8qBrF,OAAA,aAAa,WAAC;aACV,mBAAmB,aAAa,GAAG;aACnC,qBAAqB,eAAe,GAAG;aACvC,mBAAmB,YAAY,GAAG;aAClC,gBAAgB,WAAW,GAAG;QACrC,iBAAiB,GAAG;;;;;;EAYL,WAAA,QAAA,kBAAgB,QAAU;;;;;;;;;;;;;EA4BhC,aAAA,GAAG,GAAC,QACP,iBAAiB,GAAG,IAAE,WACnB,GAAC,SACH,eAAe,GAAG,IAAE,UACnB,cAAc,iBACvB,OAAO;aAEG,UAAU;eACR;eACA;eACA,QAAQ;;aAEV,SAAS;eACP;eACA;eACA,QAAQ;;KAGrB,iBACA;;;;;;;;;;EAiJO,SAAA,GAAC,UACE,gBAAgB,IAAE,kBAE3B,OAAO;aACG;aAAkC,MAAM;YAEnD;EAkCS,WAAA,GAAG,GAAC,QACL,iBAAiB,GAAG,IAAE,WACnB,GAAC,UACH,eAAe,GAAG,OAC1B,gBAAgB"}
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Effect, Queue, Schema, Stream } from "effect";
2
2
  import { QueryEvaluateError, assertSupported, evaluate, evaluate as evaluate$1, supported } from "foldkit-entity";
3
- import { RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, Remote, RemoteLiveError, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, Requirement, aliasedField, connectionIdentity, entityKey, refsIn, stableStringify } from "foldkit-remote";
3
+ import { MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Remote, RemoteJsonRequest, RemoteLiveError, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, Requirement, aliasedField, connectionIdentity, entityKey, refsIn, stableStringify } from "foldkit-remote";
4
4
  //#region src/index.ts
5
5
  /**
6
6
  * `foldkit-remote-server` — server-side Sources and handler compilation.
@@ -164,7 +164,7 @@ const liveHub = (entities) => Effect.sync(() => {
164
164
  if (record === void 0) continue;
165
165
  for (const { subscriber, fields: wanted } of group) {
166
166
  const values = Object.create(null);
167
- for (const field of wanted) if (allowedSet.has(field) && Object.hasOwn(record.values, field)) values[renames[field] ?? field] = record.values[field];
167
+ for (const field of wanted) if (allowedSet.has(field) && Object.hasOwn(record.values, field)) values[renamed(renames, field)] = record.values[field];
168
168
  const changed = Object.keys(values);
169
169
  if (changed.length === 0) continue;
170
170
  yield* emit(subscriber, {
@@ -196,6 +196,11 @@ const protocolMismatch = (received) => received === REMOTE_PROTOCOL_VERSION ? vo
196
196
  expected: REMOTE_PROTOCOL_VERSION,
197
197
  received
198
198
  });
199
+ /**
200
+ * The name a field is answered under. A requested field is client input, so
201
+ * `constructor` must find no rename rather than `Object.prototype`'s.
202
+ */
203
+ const renamed = (renames, field) => Object.hasOwn(renames, field) ? renames[field] : field;
199
204
  const pickNames = (record, names) => {
200
205
  if (record === void 0) return void 0;
201
206
  const picked = names.flatMap((name) => Object.hasOwn(record, name) ? [[name, record[name]]] : []);
@@ -212,11 +217,12 @@ const splitAliases = (request) => {
212
217
  const aliases = request.fields.filter((field) => field.includes(RELATION_ALIAS));
213
218
  if (aliases.length === 0) return [request];
214
219
  const plain = request.fields.filter((field) => !field.includes(RELATION_ALIAS));
220
+ const keyed = (entries) => Object.assign(Object.create(null), entries);
215
221
  const building = [{
216
222
  fields: [...plain],
217
- windows: { ...pickNames(request.windows, plain) },
218
- relations: { ...pickNames(request.relations, plain) },
219
- renames: {}
223
+ windows: keyed(pickNames(request.windows, plain)),
224
+ relations: keyed(pickNames(request.relations, plain)),
225
+ renames: keyed()
220
226
  }];
221
227
  for (const alias of aliases) {
222
228
  const window = request.windows?.[alias];
@@ -226,9 +232,9 @@ const splitAliases = (request) => {
226
232
  if (part === void 0) {
227
233
  part = {
228
234
  fields: [],
229
- windows: {},
230
- relations: {},
231
- renames: {}
235
+ windows: keyed(),
236
+ relations: keyed(),
237
+ renames: keyed()
232
238
  };
233
239
  building.push(part);
234
240
  }
@@ -337,10 +343,15 @@ const pageOf = (items, window, idOf, locate) => {
337
343
  * supplies a source for it. Mutations are yours to give: each one writes
338
344
  * through the store it is handed, and the next read sees the change.
339
345
  *
340
- * It does not push live changes, and it authorizes nothing: every field of
341
- * every row is readable. It is not a server to deploy.
346
+ * Every field of every row is readable unless `authorize` names the entity:
347
+ * then its function decides, per principal, as `RemoteServer.entity`'s does.
348
+ * The `layer` answers as `principal`; `server` answers as any. It does not
349
+ * push live changes. It is not a server to deploy.
342
350
  */
343
351
  const memory = (config) => {
352
+ const authorize = config.authorize ?? {};
353
+ const unknown = Object.keys(authorize).filter((name) => !config.domain.registry.entities.has(name));
354
+ if (unknown.length > 0) throw new Error(`RemoteServer.memory: \`authorize\` names ${unknown.map((name) => `"${name}"`).join(", ")}, which the domain does not declare`);
344
355
  const tables = /* @__PURE__ */ new Map();
345
356
  const table = (entity) => {
346
357
  const existing = tables.get(entity);
@@ -388,17 +399,20 @@ const memory = (config) => {
388
399
  hasPrevious: page.start._tag === "Cursor"
389
400
  };
390
401
  };
391
- const entities = [...config.domain.registry.entities.keys()].map((name) => RemoteServer.entity({ name }, { read: ({ ids, fields, windows }) => Effect.try({
392
- try: () => ids.flatMap((id) => {
393
- const row = table(name).get(id);
394
- if (row === void 0) return [];
395
- return [{
396
- id,
397
- values: Object.fromEntries(fields.flatMap((field) => field in row ? [[field, valueFor(row[field], windows?.[field])]] : []))
398
- }];
399
- }),
400
- catch: (error) => new RemoteServerError({ message: error instanceof Error ? error.message : String(error) })
401
- }) }));
402
+ const entities = [...config.domain.registry.entities.keys()].map((name) => RemoteServer.entity({ name }, {
403
+ ...Object.hasOwn(authorize, name) ? { authorize: authorize[name] } : {},
404
+ read: ({ ids, fields, windows }) => Effect.try({
405
+ try: () => ids.flatMap((id) => {
406
+ const row = table(name).get(id);
407
+ if (row === void 0) return [];
408
+ return [{
409
+ id,
410
+ values: Object.fromEntries(fields.flatMap((field) => Object.hasOwn(row, field) ? [[field, valueFor(row[field], windows?.[field])]] : []))
411
+ }];
412
+ }),
413
+ catch: (error) => new RemoteServerError({ message: error instanceof Error ? error.message : String(error) })
414
+ })
415
+ }));
402
416
  const given = new Set((config.queries ?? []).map((source) => source.query));
403
417
  const bodiless = [...config.domain.registry.queries.values()].filter((query) => query.body === void 0 && !given.has(query.name));
404
418
  if (bodiless.length > 0) throw new Error(`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\`.`);
@@ -443,7 +457,8 @@ const memory = (config) => {
443
457
  });
444
458
  return {
445
459
  ...store,
446
- layer: Remote.clientLayer(RemoteServer.handlers(server, void 0))
460
+ server,
461
+ layer: Remote.clientLayer(RemoteServer.handlers(server, config.principal))
447
462
  };
448
463
  };
449
464
  const RemoteServer = {
@@ -456,13 +471,14 @@ const RemoteServer = {
456
471
  /** A mutation outcome's report that `ref` left the connection. */
457
472
  remove: (connection, ref) => connectionChange(connection, ref, "remove"),
458
473
  /**
459
- * An entity source. Given the Entity (or anything with its `name` and
460
- * `fields`), a request for a field the entity does not declare never
461
- * reaches `read` or `authorize`.
474
+ * An entity source. Given the Entity, every member it declares (fields,
475
+ * relations, derived members) may be requested; given anything with a
476
+ * `name` and `fields`, those fields. A request for anything else never
477
+ * reaches `read` or `authorize`. Given only a `name`, every field passes.
462
478
  */
463
479
  entity: (entity, options) => ({
464
480
  entity: entity.name,
465
- ...entity.fields === void 0 ? {} : { fields: new Set(Object.keys(entity.fields)) },
481
+ ...(entity.members ?? entity.fields) === void 0 ? {} : { fields: new Set(Object.keys(entity.members ?? entity.fields)) },
466
482
  read: options.read,
467
483
  ...options.authorize === void 0 ? {} : { authorize: options.authorize }
468
484
  }),
@@ -587,7 +603,7 @@ const RemoteServer = {
587
603
  const allowed = allowedFields(source, principal, slice.fields);
588
604
  const allowedSet = new Set(allowed);
589
605
  const idList = [...ids.keys()];
590
- for (const [id, asked] of ids) settle(name, id, [...asked].filter((field) => !allowedSet.has(field)).map((field) => renames[field] ?? field));
606
+ for (const [id, asked] of ids) settle(name, id, [...asked].filter((field) => !allowedSet.has(field)).map((field) => renamed(renames, field)));
591
607
  if (allowed.length === 0) continue;
592
608
  const windows = windowsOf(slice.windows, allowed);
593
609
  const records = [];
@@ -601,8 +617,8 @@ const RemoteServer = {
601
617
  const values = Object.create(null);
602
618
  const omitted = [];
603
619
  const asked = ids.get(record.id);
604
- for (const field of allowed) if (Object.hasOwn(record.values, field)) values[renames[field] ?? field] = record.values[field];
605
- else if (asked?.has(field) === true) omitted.push(renames[field] ?? field);
620
+ for (const field of allowed) if (Object.hasOwn(record.values, field)) values[renamed(renames, field)] = record.values[field];
621
+ else if (asked?.has(field) === true) omitted.push(renamed(renames, field));
606
622
  entities.push({
607
623
  entity: name,
608
624
  id: record.id,
@@ -611,7 +627,7 @@ const RemoteServer = {
611
627
  settle(name, record.id, omitted);
612
628
  const key = `${name}:${record.id}`;
613
629
  const known = fetched.get(key) ?? /* @__PURE__ */ new Set();
614
- for (const field of allowed) known.add(renames[field] ?? field);
630
+ for (const field of allowed) known.add(renamed(renames, field));
615
631
  fetched.set(key, known);
616
632
  fetchedValues.set(key, {
617
633
  ...fetchedValues.get(key),
@@ -637,6 +653,35 @@ const RemoteServer = {
637
653
  }))
638
654
  };
639
655
  }),
656
+ /**
657
+ * Answers one JSON request through `handlers`: what an HTTP endpoint, a
658
+ * worker or a server in the page calls with the body it received, parsed.
659
+ * The request and its payload are decoded by the protocol's own schemas
660
+ * before a handler sees them, so an operation name is one of Remote's three
661
+ * and nothing else. A body that is not a request is a 400; a handler's
662
+ * failure a 500 with its message; a defect a 500 that says nothing of it.
663
+ * `Remote.json` and `Remote.http` are the other end.
664
+ */
665
+ answer: (handlers, body) => {
666
+ const asked = {
667
+ read: (payload) => Effect.flatMap(Schema.decodeUnknownEffect(ReadBatch)(payload), handlers.FoldkitRemoteRead),
668
+ query: (payload) => Effect.flatMap(Schema.decodeUnknownEffect(QueryRequest)(payload), handlers.FoldkitRemoteQuery),
669
+ mutate: (payload) => Effect.flatMap(Schema.decodeUnknownEffect(MutationRequest)(payload), handlers.FoldkitRemoteMutate)
670
+ };
671
+ return Schema.decodeUnknownEffect(RemoteJsonRequest)(body).pipe(Effect.flatMap(({ operation, payload }) => asked[operation](payload)), Effect.map((result) => ({
672
+ status: 200,
673
+ body: { result }
674
+ })), Effect.catchTag("SchemaError", (error) => Effect.succeed({
675
+ status: 400,
676
+ body: { error: error.message }
677
+ })), Effect.catch((error) => Effect.succeed({
678
+ status: 500,
679
+ body: { error: error.message }
680
+ })), Effect.catchCause(() => Effect.succeed({
681
+ status: 500,
682
+ body: { error: "Internal error" }
683
+ })));
684
+ },
640
685
  handlers: (server, principal, options = {}) => ({
641
686
  FoldkitRemoteRead: Effect.fn("RemoteServer.FoldkitRemoteRead")(function* (payload) {
642
687
  const mismatch = protocolMismatch(payload.version);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["evaluate"],"sources":["../src/index.ts"],"sourcesContent":["/**\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.\n */\nimport { Effect, Layer, Queue, Schema, Stream } from 'effect'\nimport { evaluate, type Row } from 'foldkit-entity'\nimport {\n REMOTE_PROTOCOL_VERSION,\n Remote,\n RemoteClient,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n connectionIdentity,\n entityKey,\n refsIn,\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 RELATION_ALIAS,\n aliasedField,\n} from 'foldkit-remote'\n\nexport class RemoteServerError extends Schema.TaggedError<RemoteServerError>()(\n 'RemoteServerError',\n {\n message: Schema.String,\n },\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\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 readonly Input: Schema.Codec<unknown>\n readonly Output: Schema.Codec<unknown>\n readonly run: (context: { readonly input: unknown; readonly principal: P }) => 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,\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}\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 readonly changed: (\n ref: LiveRef,\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<void, RemoteServerError, R>\n readonly deleted: (ref: LiveRef) => Effect.Effect<void>\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>(entities: ReadonlyArray<EntitySource<P, R>>): Effect.Effect<LiveHub<P, R>> =>\n Effect.sync(() => {\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 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) =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n const source = sources.get(ref.entity)\n if (source === undefined) return\n // One source read per principal (by identity) 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<P, Map<string, ReadGroup<P>>>()\n for (const subscriber of subscribers) {\n const selected = subscriber.selected.get(key)\n if (selected === undefined) continue\n const byWindows = groups.get(subscriber.principal) ?? new Map<string, ReadGroup<P>>()\n groups.set(subscriber.principal, byWindows)\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 wanted = fields.filter(field => selected.fields.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 for (const [principal, byWindows] of groups) {\n for (const { windows, renames, entries: group } of byWindows.values()) {\n const requested = [...new Set(group.flatMap(entry => entry.fields))]\n const allowed = allowedFields(source, principal, requested)\n if (allowed.length === 0) continue\n const allowedSet = new Set(allowed)\n const records = yield* source.read({\n ids: [ref.id],\n fields: allowed,\n principal,\n ...windowsOf(windows, allowed),\n })\n const record = records.find(candidate => candidate.id === ref.id)\n if (record === undefined) continue\n for (const { subscriber, fields: wanted } of group) {\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[renames[field] ?? 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 }\n }),\n\n deleted: ref =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n for (const subscriber of subscribers) {\n if (!subscriber.selected.has(key)) continue\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n }\n }),\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\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 const first: Building = {\n fields: [...plain],\n windows: { ...pickNames(request.windows, plain) },\n relations: { ...pickNames(request.relations, plain) },\n renames: {},\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: {}, relations: {}, renames: {} }\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/** A descriptor's name and, when it declares them, its fields. */\ninterface EntityName {\n readonly name: string\n readonly fields?: 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\nexport interface MemoryBackend extends MemoryStore {\n /** A `RemoteClient` answering from the rows. Provide it where the real one would go. */\n readonly layer: Layer.Layer<RemoteClient>\n}\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 * It does not push live changes, and it authorizes nothing: every field of\n * every row is readable. It is not a server to deploy.\n */\nconst memory = (config: {\n readonly domain: Pick<RemoteDescriptor, 'registry'>\n readonly rows: MemoryRows\n readonly queries?: ReadonlyArray<QuerySource<undefined>>\n readonly mutations?: (store: MemoryStore) => ReadonlyArray<MutationSource<undefined>>\n}): MemoryBackend => {\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 const entities = [...config.domain.registry.entities.keys()].map(name =>\n RemoteServer.entity<undefined>(\n { name },\n {\n read: ({ ids, fields, windows }) =>\n Effect.try({\n try: () =>\n ids.flatMap(id => {\n const row = table(name).get(id)\n if (row === undefined) return []\n const values = Object.fromEntries(\n fields.flatMap(field =>\n field in row ? [[field, valueFor(row[field], windows?.[field])] as const] : [],\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 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 RemoteServer.query<undefined>(query, ({ input, window }) =>\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>\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 const server = RemoteServer.make<undefined>({\n entities,\n queries,\n mutations: config.mutations?.(store) ?? [],\n })\n return {\n ...store,\n layer: Remote.clientLayer(\n RemoteServer.handlers(server, undefined),\n ) as Layer.Layer<RemoteClient>,\n }\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 (or anything with its `name` and\n * `fields`), a request for a field the entity does not declare never\n * reaches `read` or `authorize`.\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 },\n ): EntitySource<P, R> => ({\n entity: entity.name,\n ...(entity.fields === undefined ? {} : { fields: new Set(Object.keys(entity.fields)) }),\n read: options.read,\n ...(options.authorize === undefined ? {} : { authorize: options.authorize }),\n }),\n\n mutation: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n >(\n mutation: MutationDescriptor<Name, Input, Output>,\n run: (context: {\n readonly input: Input\n readonly principal: P\n }) => Effect.Effect<MutationOutcome<Output>, RemoteServerError, R>,\n ): MutationSource<P, R> => ({\n mutation: mutation.name,\n Input: mutation.Input,\n Output: mutation.Output,\n run: context =>\n run({ input: context.input as Input, principal: context.principal }).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 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`, then\n * call `hub.changed(ref, fields)` from wherever the data changes (a mutation\n * source, a database trigger); each subscriber that selects any of those\n * fields receives them, re-read through the entity source under its own\n * principal. It needs only the entity sources, so the mutation sources that\n * signal it can be built after it.\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 * Compiles the server into the `Read`/`Mutate` RPC handlers. `principal` is\n * resolved outside (authentication middleware in a later phase); unknown\n * entities, entities with no allowed fields, and unknown mutations return an\n * error or nothing rather than leaking existence.\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 => renames[field] ?? field),\n )\n }\n if (allowed.length === 0) continue\n\n const windows = windowsOf(slice.windows, allowed)\n const records: EntityRecord[] = []\n for (let start = 0; start < idList.length; start += maxIds) {\n records.push(\n ...(yield* source\n .read({\n ids: idList.slice(start, start + maxIds),\n fields: allowed,\n principal,\n ...windows,\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n )),\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[renames[field] ?? field] = record.values[field]\n else if (asked?.has(field) === true) omitted.push(renames[field] ?? 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(renames[field] ?? 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 handlers: <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R> = {},\n ): RemoteRpcClient<R> => ({\n FoldkitRemoteRead: Effect.fn('RemoteServer.FoldkitRemoteRead')(function* (payload) {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return yield* mismatch\n return yield* RemoteServer.readHelper(server, principal, 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 outcome = yield* source\n .run({ input, principal })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\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 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 page = yield* source\n .run({\n input,\n window: payload.window,\n principal,\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, principal, 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 const entities = [...new Set(payload.requirements.map(request => request.entity))]\n const streams: Array<Stream.Stream<LiveChangeValue, RemoteServerError, R>> = entities.flatMap(\n 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,\n }),\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,\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\nexport * from './evaluate.js'\n"],"mappings":";;;;;;;;;;;AAsCA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;AA6BH,MAAM,oBACJ,YACA,KACA,aACqB;CACrB,MAAM,OAAO;EAAE,QAAQ,IAAI;EAAQ,IAAI,IAAI;EAAI,KAAK,UAAU,IAAI,QAAQ,IAAI,EAAE;CAAE;CAClF,OAAO,aAAa,WAChB;EAAE,MAAM;EAAU,YAAY,mBAAmB,UAAU;EAAG;CAAK,IACnE;EAAE,MAAM;EAAU,YAAY,mBAAmB,UAAU;EAAG;EAAU;CAAK;AACnF;;;;;;AAOA,MAAM,iBACJ,QACA,WACA,cAC0B;CAC1B,MAAM,WACJ,OAAO,WAAW,KAAA,IAAY,YAAY,UAAU,QAAO,UAAS,OAAO,OAAQ,IAAI,KAAK,CAAC;CAC/F,IAAI,SAAS,WAAW,GAAG,OAAO,CAAC;CACnC,MAAM,YAAY,IAAI,IACpB,OAAO,cAAc,KAAA,IAAY,WAAW,OAAO,UAAU,WAAW,QAAQ,CAClF;CACA,OAAO,SAAS,QAAO,UAAS,UAAU,IAAI,KAAK,CAAC;AACtD;;AAGA,MAAM,aACJ,SACA,WACiE;CACjE,IAAI,YAAY,KAAA,GAAW,OAAO,CAAC;CACnC,MAAM,OAAO,OAAO,YAClB,OAAO,SAAQ,UACb,OAAO,OAAO,SAAS,KAAK,IAAI,CAAC,CAAC,OAAO,QAAQ,MAAO,CAAU,IAAI,CAAC,C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src/index.ts"],"sourcesContent":["/**\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.\n */\nimport { Effect, Layer, Queue, Schema, Stream } from 'effect'\nimport { evaluate, type Row } from 'foldkit-entity'\nimport {\n REMOTE_PROTOCOL_VERSION,\n Remote,\n RemoteClient,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n connectionIdentity,\n entityKey,\n refsIn,\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'\n\n/** What a call `RemoteServer.answer` makes can fail with, before the answer says so. */\ntype AnswerError =\n | Schema.SchemaError\n | RemoteReadError\n | RemoteQueryError\n | RemoteMutationError\n | RemoteProtocolError\n\nexport class RemoteServerError extends Schema.TaggedError<RemoteServerError>()(\n 'RemoteServerError',\n {\n message: Schema.String,\n },\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\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 readonly Input: Schema.Codec<unknown>\n readonly Output: Schema.Codec<unknown>\n readonly run: (context: { readonly input: unknown; readonly principal: P }) => 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,\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}\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 readonly changed: (\n ref: LiveRef,\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<void, RemoteServerError, R>\n readonly deleted: (ref: LiveRef) => Effect.Effect<void>\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>(entities: ReadonlyArray<EntitySource<P, R>>): Effect.Effect<LiveHub<P, R>> =>\n Effect.sync(() => {\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 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) =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n const source = sources.get(ref.entity)\n if (source === undefined) return\n // One source read per principal (by identity) 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<P, Map<string, ReadGroup<P>>>()\n for (const subscriber of subscribers) {\n const selected = subscriber.selected.get(key)\n if (selected === undefined) continue\n const byWindows = groups.get(subscriber.principal) ?? new Map<string, ReadGroup<P>>()\n groups.set(subscriber.principal, byWindows)\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 wanted = fields.filter(field => selected.fields.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 for (const [principal, byWindows] of groups) {\n for (const { windows, renames, entries: group } of byWindows.values()) {\n const requested = [...new Set(group.flatMap(entry => entry.fields))]\n const allowed = allowedFields(source, principal, requested)\n if (allowed.length === 0) continue\n const allowedSet = new Set(allowed)\n const records = yield* source.read({\n ids: [ref.id],\n fields: allowed,\n principal,\n ...windowsOf(windows, allowed),\n })\n const record = records.find(candidate => candidate.id === ref.id)\n if (record === undefined) continue\n for (const { subscriber, fields: wanted } of group) {\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 }\n }),\n\n deleted: ref =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n for (const subscriber of subscribers) {\n if (!subscriber.selected.has(key)) continue\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n }\n }),\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\nexport interface MemoryBackend<P = undefined> extends MemoryStore {\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 * The server the layer answers through, for serving the rows over a real\n * transport, or as another principal:\n * `RemoteRpc.toLayer(RemoteServer.handlers(backend.server, principal))`.\n */\n readonly server: ServerDefinition<P>\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 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} & (undefined extends P\n ? { readonly principal?: P }\n : {\n /** Who the `layer` answers as. */\n readonly principal: P\n })\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 * The `layer` answers as `principal`; `server` answers as any. It does not\n * push live changes. It is not a server to deploy.\n */\nconst memory = <P = undefined>(config: MemoryConfig<P>): MemoryBackend<P> => {\n const authorize = config.authorize ?? {}\n const unknown = Object.keys(authorize).filter(name => !config.domain.registry.entities.has(name))\n if (unknown.length > 0) {\n throw new Error(\n `RemoteServer.memory: \\`authorize\\` names ${unknown.map(name => `\"${name}\"`).join(', ')}, which the domain does not declare`,\n )\n }\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 const entities = [...config.domain.registry.entities.keys()].map(name =>\n RemoteServer.entity<P>(\n { name },\n {\n ...(Object.hasOwn(authorize, name) ? { authorize: authorize[name]! } : {}),\n read: ({ ids, fields, windows }) =>\n Effect.try({\n try: () =>\n ids.flatMap(id => {\n const row = table(name).get(id)\n if (row === undefined) return []\n const values = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(row, field)\n ? [[field, valueFor(row[field], windows?.[field])] as const]\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 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 RemoteServer.query<P>(query, ({ input, window }) =>\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>\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 const server = RemoteServer.make<P>({\n entities,\n queries,\n mutations: config.mutations?.(store) ?? [],\n })\n return {\n ...store,\n server,\n layer: Remote.clientLayer(\n // `principal` is required by the config's type unless `P` admits undefined.\n RemoteServer.handlers(server, config.principal as P),\n ) as Layer.Layer<RemoteClient>,\n }\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 },\n ): EntitySource<P, R> => ({\n entity: entity.name,\n ...((entity.members ?? entity.fields) === undefined\n ? {}\n : { fields: new Set(Object.keys(entity.members ?? entity.fields!)) }),\n read: options.read,\n ...(options.authorize === undefined ? {} : { authorize: options.authorize }),\n }),\n\n mutation: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n >(\n mutation: MutationDescriptor<Name, Input, Output>,\n run: (context: {\n readonly input: Input\n readonly principal: P\n }) => Effect.Effect<MutationOutcome<Output>, RemoteServerError, R>,\n ): MutationSource<P, R> => ({\n mutation: mutation.name,\n Input: mutation.Input,\n Output: mutation.Output,\n run: context =>\n run({ input: context.input as Input, principal: context.principal }).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 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`, then\n * call `hub.changed(ref, fields)` from wherever the data changes (a mutation\n * source, a database trigger); each subscriber that selects any of those\n * fields receives them, re-read through the entity source under its own\n * principal. It needs only the entity sources, so the mutation sources that\n * signal it can be built after it.\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 * Compiles the server into the `Read`/`Mutate` RPC handlers. `principal` is\n * resolved outside (authentication middleware in a later phase); unknown\n * entities, entities with no allowed fields, and unknown mutations return an\n * error or nothing rather than leaking existence.\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: EntityRecord[] = []\n for (let start = 0; start < idList.length; start += maxIds) {\n records.push(\n ...(yield* source\n .read({\n ids: idList.slice(start, start + maxIds),\n fields: allowed,\n principal,\n ...windows,\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n )),\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 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 | 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.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 handlers: <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R> = {},\n ): RemoteRpcClient<R> => ({\n FoldkitRemoteRead: Effect.fn('RemoteServer.FoldkitRemoteRead')(function* (payload) {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return yield* mismatch\n return yield* RemoteServer.readHelper(server, principal, 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 outcome = yield* source\n .run({ input, principal })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\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 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 page = yield* source\n .run({\n input,\n window: payload.window,\n principal,\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, principal, 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 const entities = [...new Set(payload.requirements.map(request => request.entity))]\n const streams: Array<Stream.Stream<LiveChangeValue, RemoteServerError, R>> = entities.flatMap(\n 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,\n }),\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,\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\nexport * from './evaluate.js'\n"],"mappings":";;;;;;;;;;;AAmDA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;AA6BH,MAAM,oBACJ,YACA,KACA,aACqB;CACrB,MAAM,OAAO;EAAE,QAAQ,IAAI;EAAQ,IAAI,IAAI;EAAI,KAAK,UAAU,IAAI,QAAQ,IAAI,EAAE;CAAE;CAClF,OAAO,aAAa,WAChB;EAAE,MAAM;EAAU,YAAY,mBAAmB,UAAU;EAAG;CAAK,IACnE;EAAE,MAAM;EAAU,YAAY,mBAAmB,UAAU;EAAG;EAAU;CAAK;AACnF;;;;;;AAOA,MAAM,iBACJ,QACA,WACA,cAC0B;CAC1B,MAAM,WACJ,OAAO,WAAW,KAAA,IAAY,YAAY,UAAU,QAAO,UAAS,OAAO,OAAQ,IAAI,KAAK,CAAC;CAC/F,IAAI,SAAS,WAAW,GAAG,OAAO,CAAC;CACnC,MAAM,YAAY,IAAI,IACpB,OAAO,cAAc,KAAA,IAAY,WAAW,OAAO,UAAU,WAAW,QAAQ,CAClF;CACA,OAAO,SAAS,QAAO,UAAS,UAAU,IAAI,KAAK,CAAC;AACtD;;AAGA,MAAM,aACJ,SACA,WACiE;CACjE,IAAI,YAA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AQ,SAAS,KAAA,GACnB,QAAQ,KACN,QAAQ,KAAK,UAAU;IACrB,cAAc,QAAQ;IACtB,OAAO,QAAQ;IACf;IACA,iBAAiB,QAAQ;GAC3B,CAAC,CACH;GAIF,OAAO,OAAO,SAAS,SAAS,EAAE,aAAa,YAAY,CAAC,CAAC,CAAC,KAC5D,OAAO,UAAS,UAAS,IAAI,gBAAgB,EAAE,SAAS,MAAM,QAAQ,CAAC,CAAC,CAC1E;EACF;CACF;AACF"}
@@ -0,0 +1,13 @@
1
+ import { Effect, Scope } from "effect";
2
+ import { RemoteRpcClient } from "foldkit-remote";
3
+ import { WorkerError } from "effect/workers/WorkerError";
4
+ //#region src/port.d.ts
5
+ /**
6
+ * Serves `handlers` (`RemoteServer.handlers(...)`) over `port`, returning once
7
+ * the client closes its end; interrupt it to stop sooner. Provide what the
8
+ * handlers need. It fails with a `WorkerError` only when the port itself
9
+ * breaks.
10
+ */
11
+ export declare const servePort: <R>(handlers: RemoteRpcClient<R>, port: MessagePort) => Effect.Effect<void, WorkerError, Exclude<R, Scope.Scope>>;
12
+ //#endregion
13
+ //# sourceMappingURL=port.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"port.d.mts","names":[],"sources":["../src/port.ts"],"mappings":";;;;;;;;;;qBAkBa,YAAa,GACxB,UAAU,gBAAgB,IAC1B,MAAM,gBACL,OAAO,aAAa,aAAa,QAAQ,GAAG,MAAM"}
package/dist/port.mjs ADDED
@@ -0,0 +1,25 @@
1
+ import { Effect, Layer } from "effect";
2
+ import { RemoteRpc } from "foldkit-remote";
3
+ import { RpcServer } from "effect/rpc";
4
+ import * as WorkerRunner from "effect/workers/WorkerRunner";
5
+ import { portRunner } from "foldkit-remote/port";
6
+ //#region src/port.ts
7
+ /**
8
+ * `foldkit-remote-server/port`: `RemoteServer`'s handlers answering over a
9
+ * `MessagePort`, the other end of `foldkit-remote/port`'s `port`. A host in a
10
+ * worker or a page hands it the port each conversation opens.
11
+ */
12
+ /**
13
+ * Serves `handlers` (`RemoteServer.handlers(...)`) over `port`, returning once
14
+ * the client closes its end; interrupt it to stop sooner. Provide what the
15
+ * handlers need. It fails with a `WorkerError` only when the port itself
16
+ * breaks.
17
+ */
18
+ const servePort = (handlers, port) => {
19
+ const { platform, closed } = portRunner(port);
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
+ };
22
+ //#endregion
23
+ export { servePort };
24
+
25
+ //# sourceMappingURL=port.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"port.mjs","names":[],"sources":["../src/port.ts"],"sourcesContent":["/**\n * `foldkit-remote-server/port`: `RemoteServer`'s handlers answering over a\n * `MessagePort`, the other end of `foldkit-remote/port`'s `port`. A host in a\n * worker or a page hands it the port each conversation opens.\n */\nimport { Effect, Layer, type Scope } from 'effect'\nimport { RpcServer } from 'effect/rpc'\nimport type { WorkerError } from 'effect/workers/WorkerError'\nimport * as WorkerRunner from 'effect/workers/WorkerRunner'\nimport { RemoteRpc, type RemoteRpcClient } from 'foldkit-remote'\nimport { portRunner } from 'foldkit-remote/port'\n\n/**\n * Serves `handlers` (`RemoteServer.handlers(...)`) over `port`, returning once\n * the client closes its end; interrupt it to stop sooner. Provide what the\n * handlers need. It fails with a `WorkerError` only when the port itself\n * breaks.\n */\nexport const servePort = <R>(\n handlers: RemoteRpcClient<R>,\n port: MessagePort,\n): Effect.Effect<void, WorkerError, Exclude<R, Scope.Scope>> => {\n const { platform, closed } = portRunner(port)\n return Effect.scoped(\n Layer.build(\n RpcServer.layer(RemoteRpc).pipe(\n Layer.provide(RemoteRpc.toLayer(handlers)),\n Layer.provide(RpcServer.layerProtocolWorkerRunner),\n Layer.provide(Layer.succeed(WorkerRunner.WorkerRunnerPlatform)(platform)),\n ),\n ).pipe(Effect.andThen(closed)),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAa,aACX,UACA,SAC8D;CAC9D,MAAM,EAAE,UAAU,WAAW,WAAW,IAAI;CAC5C,OAAO,OAAO,OACZ,MAAM,MACJ,UAAU,MAAM,SAAS,CAAC,CAAC,KACzB,MAAM,QAAQ,UAAU,QAAQ,QAAQ,CAAC,GACzC,MAAM,QAAQ,UAAU,yBAAyB,GACjD,MAAM,QAAQ,MAAM,QAAQ,aAAa,oBAAoB,CAAC,CAAC,QAAQ,CAAC,CAC1E,CACF,CAAC,CAAC,KAAK,OAAO,QAAQ,MAAM,CAAC,CAC/B;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-remote-server",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Server sources and handler compilation for foldkit-remote: entities, selection authorization, and normalization.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -31,6 +31,11 @@
31
31
  "foldkit-plus:source": "./src/index.ts",
32
32
  "types": "./dist/index.d.mts",
33
33
  "import": "./dist/index.mjs"
34
+ },
35
+ "./port": {
36
+ "foldkit-plus:source": "./src/port.ts",
37
+ "types": "./dist/port.d.mts",
38
+ "import": "./dist/port.mjs"
34
39
  }
35
40
  },
36
41
  "files": [
@@ -39,8 +44,8 @@
39
44
  "LICENSE"
40
45
  ],
41
46
  "dependencies": {
42
- "foldkit-entity": "0.6.0",
43
- "foldkit-remote": "0.10.0"
47
+ "foldkit-remote": "0.12.0",
48
+ "foldkit-entity": "0.7.0"
44
49
  },
45
50
  "peerDependencies": {
46
51
  "effect": "^4.0.0"
@@ -51,7 +56,7 @@
51
56
  "foldkit": "0.165.0",
52
57
  "tsdown": "^0.23.0",
53
58
  "typescript": "5.9.3",
54
- "foldkit-surface": "0.6.0"
59
+ "foldkit-surface": "0.7.0"
55
60
  },
56
61
  "scripts": {
57
62
  "build": "tsdown",