foldkit-remote-server 0.18.0 → 0.20.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.
@@ -1,6 +1,46 @@
1
- import { Context, Effect, Match, Option, Queue, Schema, Stream } from "effect";
2
- import { Entity, Operators, QueryEvaluateError, SchemaShape, Write, assertSupported, assertSupported as assertSupported$1, evaluate, evaluate as evaluate$1, supported } from "foldkit-entity";
3
- import { MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Remote, RemoteForbidden, RemoteJsonRequest, RemoteLiveError, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, RemoteUnauthenticated, Requirement, aliasedField, connectionIdentity, entityKey, refParts, refsIn, relationShape, stableStringify } from "foldkit-remote";
1
+ import { Cause, Clock, Context, Data, Duration, Effect, Match, Option, Queue, Schema, Stream } from "effect";
2
+ import { Derivation, Entity, Held, Operators, Query, QueryEvaluateError, SchemaShape, Write, assertSupported, assertSupported as assertSupported$1, evaluate, evaluate as evaluate$1, supported } from "foldkit-entity";
3
+ import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_IDS_PER_ENTITY, Diagnostics, MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Refusal, Remote, RemoteForbidden, RemoteJsonRequest, RemoteLiveError, RemoteLiveRefused, RemoteMutationError, RemotePrincipalChanged, RemoteProtocolError, RemoteQueryError, RemoteReadError, RemoteUnauthenticated, Requirement, aliasedField, connectionIdentity, entityKey, queryIdentity, refParts, refsIn, relationShape, stableStringify } from "foldkit-remote";
4
+ import { HttpServerRequest, HttpServerResponse } from "effect/http";
5
+ // src/diagnostics.ts
6
+ /**
7
+ * What a Remote server answers past without telling the caller why: a defect
8
+ * it answered "Internal error", a committed mutation whose answer's read or
9
+ * live publish failed, and a client's time it would not take. Each is
10
+ * reported through `Diagnostics.report`, so a host's log (a Worker's
11
+ * `wrangler tail`) shows it by default.
12
+ */
13
+ const source = "foldkit-remote-server";
14
+ const serverDefect = (cause) => ({
15
+ _tag: "ServerDefect",
16
+ source,
17
+ level: "error",
18
+ message: `a request failed on this side, and its caller was answered "Internal error"\n${Cause.pretty(cause)}`,
19
+ cause
20
+ });
21
+ const answerUnread = (mutation, reason) => ({
22
+ _tag: "AnswerUnread",
23
+ source,
24
+ level: "warning",
25
+ message: `${mutation} committed, but reading its answer failed (${reason}): the client reads what it lacks again.`,
26
+ mutation,
27
+ reason
28
+ });
29
+ const publishFailed = (mutation, cause) => ({
30
+ _tag: "PublishFailed",
31
+ source,
32
+ level: "error",
33
+ message: `${mutation} committed, but its live publish failed, so live subscribers do not hear it\n${Cause.pretty(cause)}`,
34
+ mutation,
35
+ cause
36
+ });
37
+ const clockSkewed = (facts) => ({
38
+ _tag: "ClockSkewed",
39
+ source,
40
+ level: "warning",
41
+ message: `${facts.mutation} was sent at ${facts.sent}, ${Math.abs(facts.sent - facts.own)} ms from this server's clock (${facts.own}), past its clockSkew of ${facts.bound} ms: it was written at the server's time, so the client's prediction of it moves when the answer lands. The client's clock is off, or the request waited that long.`,
42
+ ...facts
43
+ });
4
44
  // src/refusal.ts
5
45
  /** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */
6
46
  const unauthenticatedAnswer = (refusal) => ({
@@ -10,6 +50,105 @@ const unauthenticatedAnswer = (refusal) => ({
10
50
  unauthenticated: refusal.reason === void 0 ? {} : { reason: refusal.reason }
11
51
  }
12
52
  });
53
+ // src/body.ts
54
+ /**
55
+ * A request body read up to a limit, refused past it before anything decodes
56
+ * it: what `serveFetch` and `bodyLimit` share. The limit is checked against
57
+ * `content-length` before a byte is read, and against the bytes as they
58
+ * arrive, so a body without one, or with one that lies, is cancelled the
59
+ * moment it passes the limit rather than buffered whole.
60
+ */
61
+ /** The body passed the limit; nothing past it was kept. */
62
+ var BodyTooLarge = class extends Error {};
63
+ /** Remote's answer to a body over `limit`, sent as a 413. */
64
+ const tooLargeAnswer = (limit) => ({
65
+ error: `The request body is larger than ${limit} bytes`,
66
+ tooLarge: { limit }
67
+ });
68
+ /** Whether `request` says it is larger than `limit`, before any of it is read. */
69
+ const declaresTooLarge = (request, limit) => {
70
+ const length = Number(request.headers.get("content-length") ?? NaN);
71
+ return Number.isFinite(length) && length > limit;
72
+ };
73
+ /**
74
+ * `request`'s body, at most `limit` bytes of it. Rejects with `BodyTooLarge`
75
+ * once more arrive, having cancelled the rest, or with the stream's own error.
76
+ */
77
+ const readBounded = async (request, limit) => {
78
+ if (declaresTooLarge(request, limit)) throw new BodyTooLarge();
79
+ if (request.body === null) return /* @__PURE__ */ new Uint8Array();
80
+ const reader = request.body.getReader();
81
+ const chunks = [];
82
+ let total = 0;
83
+ for (;;) {
84
+ const { done, value } = await reader.read();
85
+ if (done) break;
86
+ total += value.byteLength;
87
+ if (total > limit) {
88
+ await reader.cancel();
89
+ throw new BodyTooLarge();
90
+ }
91
+ chunks.push(value);
92
+ }
93
+ const body = new Uint8Array(total);
94
+ let offset = 0;
95
+ for (const chunk of chunks) {
96
+ body.set(chunk, offset);
97
+ offset += chunk.byteLength;
98
+ }
99
+ return body;
100
+ };
101
+ const BoundedBody = Data.taggedEnum();
102
+ /** `request`'s body read up to `limit` bytes; never fails. */
103
+ const readBody = (request, limit) => Effect.tryPromise(() => readBounded(request, limit)).pipe(Effect.match({
104
+ onSuccess: (bytes) => BoundedBody.Read({ bytes }),
105
+ onFailure: (error) => error.cause instanceof BodyTooLarge ? BoundedBody.TooLarge() : BoundedBody.Unreadable()
106
+ }));
107
+ /** A body refused before any handler: the status and Remote's answer. */
108
+ var BodyRefused = class extends Data.TaggedError("BodyRefused") {};
109
+ /** Decodes a body as UTF-8, refusing bytes that are not, as `JSON.parse` would refuse the text. */
110
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
111
+ /** `request`'s body read up to `limit` bytes and parsed as JSON, or refused. */
112
+ const readJson = (request, limit) => {
113
+ const notJson = new BodyRefused({
114
+ status: 400,
115
+ answer: { error: "The body is not JSON" }
116
+ });
117
+ return Effect.flatMap(readBody(request, limit), (body) => BoundedBody.$match(body, {
118
+ Read: ({ bytes }) => Effect.try({
119
+ try: () => JSON.parse(utf8.decode(bytes)),
120
+ catch: () => notJson
121
+ }),
122
+ TooLarge: () => Effect.fail(new BodyRefused({
123
+ status: 413,
124
+ answer: tooLargeAnswer(limit)
125
+ })),
126
+ Unreadable: () => Effect.fail(notJson)
127
+ }));
128
+ };
129
+ /**
130
+ * Effect HTTP middleware refusing a request body over `maxBytes` (default
131
+ * 1 MiB, `serveFetch`'s) with a 413 and Remote's `tooLarge` answer, before
132
+ * the endpoint reads it. For an endpoint that serves `RemoteRpc` through
133
+ * `RpcServer`, where Effect's own `MaxBodySize` fails the body read as a
134
+ * defect, a 500:
135
+ *
136
+ * ```ts
137
+ * HttpRouter.add('POST', '/rpc', bodyLimit(64 * 1024)(rpcHttpEffect))
138
+ * ```
139
+ *
140
+ * A body within the limit reaches the endpoint whole, read once.
141
+ */
142
+ const bodyLimit = (maxBytes = DEFAULT_MAX_BODY_BYTES) => (endpoint) => Effect.gen(function* () {
143
+ const request = yield* HttpServerRequest.HttpServerRequest;
144
+ const web = yield* Effect.orDie(HttpServerRequest.toWeb(request));
145
+ const body = yield* readBody(web, maxBytes);
146
+ return yield* BoundedBody.$match(body, {
147
+ TooLarge: () => Effect.succeed(HttpServerResponse.jsonUnsafe(tooLargeAnswer(maxBytes), { status: 413 })),
148
+ Unreadable: () => Effect.succeed(HttpServerResponse.jsonUnsafe({ error: "The body could not be read" }, { status: 400 })),
149
+ Read: ({ bytes }) => Effect.provideService(endpoint, HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(new Request(web, { body: bytes })))
150
+ });
151
+ });
13
152
  // src/index.ts
14
153
  /**
15
154
  * `foldkit-remote-server` — server-side Sources and handler compilation.
@@ -26,6 +165,13 @@ var RemoteServerError = class extends Schema.TaggedError()("RemoteServerError",
26
165
  */
27
166
  var RemoteUnmet = class extends Schema.TaggedError()("RemoteUnmet", { message: Schema.String }) {};
28
167
  /**
168
+ * A writer's word that a row already holds the id an insert names, and its
169
+ * ledger records no insert of this operation that made it: `RemoteServer.write`
170
+ * answers it as the mutation's `Taken` refusal. It says nothing of the row,
171
+ * which may be hidden from whoever asked.
172
+ */
173
+ var RemoteTaken = class extends Schema.TaggedError()("RemoteTaken", { message: Schema.String }) {};
174
+ /**
29
175
  * A writer's word that the row a write would leave breaks one of its Entity's
30
176
  * invariants: `RemoteServer.write` answers it as the mutation's `Invalid`
31
177
  * refusal. `rule` and `path` are none and empty when saying them would tell
@@ -50,6 +196,33 @@ var MutationRefused = class extends Schema.TaggedError()("MutationRefused", {
50
196
  }) {};
51
197
  /** `source.read` of `fields`, through the source's `filter` when it has one. */
52
198
  const readFiltered = (source, principal, fields, read) => source.filter === void 0 ? read(fields) : Effect.flatMap(source.filter(principal, fields), (plan) => Effect.map(read(plan.fields), (records) => records.map(plan.apply)));
199
+ /**
200
+ * A read as the handlers make it for `context.principal`: the asked fields the
201
+ * source declares and `authorize` allows, through `filter`, each record holding
202
+ * no other field. None when the principal may read none of the fields asked,
203
+ * so a caller can tell nothing to read from a row that is gone.
204
+ */
205
+ const readAs = (source, context) => {
206
+ const { ids, principal, viewer } = context;
207
+ const allowed = allowedFields(source, principal, context.fields);
208
+ if (allowed.length === 0) return Effect.succeed(Option.none());
209
+ return readFiltered(source, principal, allowed, (fields) => source.read({
210
+ ids,
211
+ fields,
212
+ principal,
213
+ viewer,
214
+ ...windowsOf(context.windows, allowed)
215
+ })).pipe(Effect.map((records) => Option.some(records.map((record) => {
216
+ const values = Object.create(null);
217
+ for (const field of allowed) if (Object.hasOwn(record.values, field)) values[field] = record.values[field];
218
+ return {
219
+ id: record.id,
220
+ values
221
+ };
222
+ }))));
223
+ };
224
+ const RowRequirement = Data.taggedEnum();
225
+ const DeleteOutcome = Data.taggedEnum();
53
226
  const connectionChange = (connection, ref, position) => {
54
227
  const edge = {
55
228
  entity: ref.entity,
@@ -84,11 +257,85 @@ const windowsOf = (windows, fields) => {
84
257
  const kept = Object.fromEntries(fields.flatMap((field) => Object.hasOwn(windows, field) ? [[field, windows[field]]] : []));
85
258
  return Object.keys(kept).length === 0 ? {} : { windows: kept };
86
259
  };
87
- /** A read batch may not carry more than this many distinct ids per entity. */
88
- const DEFAULT_MAX_IDS_PER_ENTITY = 1e3;
260
+ /** How far from the server's clock a client's time is taken as a write's, unless `make` says. */
261
+ const DEFAULT_CLOCK_SKEW = Duration.seconds(60);
262
+ /**
263
+ * A write's time: the client's, when it sent one within `clockSkew` of this
264
+ * server's clock, or this server's. A time refused past a bound above zero is
265
+ * reported; at zero every client time is refused by design, so none is.
266
+ */
267
+ const writeTime = (server, mutation, sent) => Effect.flatMap(Clock.currentTimeMillis, (own) => Option.match(sent, {
268
+ onNone: () => Effect.succeed(own),
269
+ onSome: (time) => {
270
+ const bound = Duration.toMillis(server.clockSkew ?? DEFAULT_CLOCK_SKEW);
271
+ if (bound === 0) return Effect.succeed(own);
272
+ return Math.abs(time - own) <= bound ? Effect.succeed(time) : Effect.as(Diagnostics.report(clockSkewed({
273
+ mutation,
274
+ sent: time,
275
+ own,
276
+ bound
277
+ })), own);
278
+ }
279
+ }));
280
+ /**
281
+ * What a body's `Expr.viewer` and `Expr.now` read on this server: the viewer
282
+ * the request was given, and the server's clock. A body that reads the viewer
283
+ * in a run given none (not through a server) is refused, never read as a
284
+ * visitor's.
285
+ */
286
+ const exprContext = (body, viewer, now) => {
287
+ if (viewer === void 0 && Query.dependencies(body).operations.includes("viewer")) throw new Error(`[foldkit-remote-server] a query of ${body.entity.name} reads Expr.viewer, but was run outside a server, which gives the viewer`);
288
+ return {
289
+ viewer: viewer ?? Option.none(),
290
+ now: Option.some(now)
291
+ };
292
+ };
293
+ /** Who asks, as the server's `viewer` says: none for a visitor, or on a server with no viewer. */
294
+ const viewerOf = (server, principal) => server.viewer === void 0 ? Option.none() : server.viewer(principal);
295
+ /**
296
+ * Whom an answer is for, as the wire says it (#405): the key of who asks
297
+ * (their `viewer`), `null` for a visitor, and nothing from a server that
298
+ * names no `viewer`, which keeps no keys.
299
+ */
300
+ const answeredFor = (server, principal) => server.viewer === void 0 ? {} : { principal: Option.match(server.viewer(principal), {
301
+ onNone: () => null,
302
+ onSome: (viewer) => entityKey(viewer.entity, viewer.id)
303
+ }) };
304
+ /**
305
+ * Refuses a write made for someone other than who asks, before anything of
306
+ * it runs (#405): one made for someone, asked by a visitor, is asked to sign
307
+ * in; any other told who is signed in changed, a visitor's (`null`) asked by
308
+ * someone signed in included. A server that keeps no keys cannot tell, and
309
+ * refuses any write that names one.
310
+ */
311
+ const madeFor = (server, principal, expected) => Option.match(expected, {
312
+ onNone: () => Effect.void,
313
+ onSome: (key) => {
314
+ const asking = answeredFor(server, principal).principal;
315
+ if (asking === key) return Effect.void;
316
+ return asking === null ? Effect.fail(RemoteServer.unauthenticated()) : Effect.fail(new RemotePrincipalChanged({ message: "The write was made for someone other than who is signed in now" }));
317
+ }
318
+ });
319
+ /**
320
+ * One row as `principal` may see it, through the server's own source for its
321
+ * Entity: the fields its `authorize` allows, filtered as the source filters.
322
+ * None for a row hidden or not there.
323
+ */
324
+ const rowAs = (server, principal) => (ref, fields) => {
325
+ const source = server.entities.get(ref.entity);
326
+ if (source === void 0) return Effect.fail(new RemoteServerError({ message: `No source serves ${ref.entity}` }));
327
+ const allowed = source.authorize?.(principal, fields) ?? fields;
328
+ return Effect.map(readFiltered(source, principal, allowed, (read) => source.read({
329
+ ids: [ref.id],
330
+ fields: read,
331
+ principal,
332
+ viewer: viewerOf(server, principal)
333
+ })), (records) => Option.map(Option.fromUndefinedOr(records[0]), (record) => record.values));
334
+ };
335
+ /** `read` with the services the request already runs with, so its caller needs none. */
336
+ const withServices = (read, services) => (...args) => Effect.provideContext(read(...args), services);
89
337
  /** A nested selection may not reach further than this many relation levels. */
90
338
  const DEFAULT_MAX_DEPTH = 8;
91
- /** Fails when the requirements name more distinct ids of one entity than `maxIds`. */
92
339
  /**
93
340
  * Each page of a relation read beside another is a source read of its own, and
94
341
  * the names come from the client, so how many one relation may have is bounded.
@@ -110,6 +357,7 @@ const checkPagesPerRelation = (requirements) => {
110
357
  if (nested !== void 0) return nested;
111
358
  }
112
359
  };
360
+ /** The entity the requirements name more distinct ids of than `maxIds`; `undefined` when none. */
113
361
  const checkIdsPerEntity = (requirements, maxIds) => {
114
362
  const ids = /* @__PURE__ */ new Map();
115
363
  for (const requirement of requirements) {
@@ -119,6 +367,58 @@ const checkIdsPerEntity = (requirements, maxIds) => {
119
367
  if (seen.size > maxIds) return requirement.entity;
120
368
  }
121
369
  };
370
+ /** Why a live subscription asks more than a read may; `undefined` when it does not. */
371
+ const liveRefusal = (requirements, maxIds) => {
372
+ const over = checkIdsPerEntity(requirements, maxIds);
373
+ if (over !== void 0) return new RemoteLiveRefused({ message: `Too many "${over}" ids in one live subscription (at most ${maxIds})` });
374
+ const paged = checkPagesPerRelation(requirements);
375
+ if (paged !== void 0) return new RemoteLiveRefused({ message: `Too many pages of "${paged}" in one live subscription` });
376
+ };
377
+ /**
378
+ * Admits each live list as a read of it is admitted, and refuses what a list
379
+ * read again every tick may not be: a query the server does not register, an
380
+ * input it does not decode, no `select` (a row is diffed by what it is drawn
381
+ * with) or one of another entity than the query lists, no `first`, or a
382
+ * `first` that, with the ids of its entity the subscription names, passes
383
+ * `maxIds`.
384
+ */
385
+ const admitQueries = (server, queries, requirements, maxIds) => Effect.gen(function* () {
386
+ const refused = (message) => new RemoteLiveRefused({ message });
387
+ const admitted = [];
388
+ const rows = /* @__PURE__ */ new Map();
389
+ for (const request of queries) {
390
+ const source = server.queries.get(request.query);
391
+ if (source === void 0) return yield* refused(`Unknown query "${request.query}" read live`);
392
+ const { select } = request;
393
+ if (select === void 0) return yield* refused(`Query "${request.query}" is read live with no select`);
394
+ if (select.entity !== source.entity) return yield* refused(`Query "${request.query}" lists "${source.entity}", but is read live selecting "${select.entity}"`);
395
+ const { first } = request.window;
396
+ if (first === void 0) return yield* refused(`Query "${request.query}" is read live with no first`);
397
+ const paged = checkPagesPerRelation([select]);
398
+ if (paged !== void 0) return yield* refused(`Too many pages of "${paged}" in one live subscription`);
399
+ const input = yield* Schema.decodeUnknownEffect(source.Input)(request.input).pipe(Effect.mapError(() => refused(`Invalid input of query "${request.query}" read live`)));
400
+ rows.set(select.entity, (rows.get(select.entity) ?? 0) + first);
401
+ admitted.push({
402
+ request,
403
+ select,
404
+ source,
405
+ input
406
+ });
407
+ }
408
+ const ids = /* @__PURE__ */ new Map();
409
+ for (const requirement of requirements) {
410
+ const seen = ids.get(requirement.entity) ?? /* @__PURE__ */ new Set();
411
+ seen.add(requirement.id);
412
+ ids.set(requirement.entity, seen);
413
+ }
414
+ for (const [entity, listed] of rows) if ((ids.get(entity)?.size ?? 0) + listed > maxIds) return yield* refused(`Too many "${entity}" ids in one live subscription (at most ${maxIds}, the rows of its live lists counted)`);
415
+ return admitted;
416
+ });
417
+ /** A subscriber's viewer as a group key: who, none for a visitor, or no server viewer. */
418
+ const viewerKeyOf = (viewer) => viewer === void 0 ? "unset" : Option.match(viewer, {
419
+ onNone: () => "visitor",
420
+ onSome: (ref) => `as ${ref.entity}:${ref.id}`
421
+ });
122
422
  const liveHub = (entities, options = {}) => Effect.sync(() => {
123
423
  const keyOf = options.key ?? ((principal) => principal);
124
424
  const sources = new Map(entities.map((source) => [source.entity, source]));
@@ -149,12 +449,14 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
149
449
  return;
150
450
  }
151
451
  const given = (field) => values !== void 0 && source.shared !== void 0 && source.shared.has(field) && Object.hasOwn(values, field);
452
+ const perViewer = (source.perViewer ?? []).length > 0;
152
453
  const groups = /* @__PURE__ */ new Map();
153
454
  for (const subscriber of subscribers) {
154
455
  const selected = subscriber.selected.get(key);
155
456
  if (selected === void 0) continue;
156
457
  const fields = Option.getOrElse(which, () => [...new Set([...selected.fields].map(aliasedField))]);
157
458
  const principalKey = keyOf(subscriber.principal);
459
+ const viewerKey = perViewer ? viewerKeyOf(subscriber.viewer) : "";
158
460
  const sharing = groups.get(principalKey) ?? {
159
461
  principal: subscriber.principal,
160
462
  byWindows: /* @__PURE__ */ new Map()
@@ -162,7 +464,7 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
162
464
  groups.set(principalKey, sharing);
163
465
  const { byWindows } = sharing;
164
466
  const join = (windows, renames, wanted) => {
165
- const groupKey = `${stableStringify(windows)}\u0000${stableStringify(renames)}`;
467
+ const groupKey = `${stableStringify(windows)}\u0000${stableStringify(renames)}\u0000${viewerKey}`;
166
468
  const group = byWindows.get(groupKey) ?? {
167
469
  windows,
168
470
  renames,
@@ -203,15 +505,16 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
203
505
  const gone = /* @__PURE__ */ new Set();
204
506
  const read = (principal, { windows, renames, entries: group }) => Effect.gen(function* () {
205
507
  const requested = [...new Set(group.flatMap((entry) => entry.fields))];
206
- const allowed = allowedFields(source, principal, requested);
207
- if (allowed.length === 0) return;
208
- const allowedSet = new Set(allowed);
209
- const record = (yield* readFiltered(source, principal, allowed, (fields) => source.read({
508
+ const viewer = group[0]?.subscriber.viewer;
509
+ const records = yield* readAs(source, {
210
510
  ids: [ref.id],
211
- fields,
511
+ fields: requested,
212
512
  principal,
213
- ...windowsOf(windows, allowed)
214
- }))).find((candidate) => candidate.id === ref.id);
513
+ viewer,
514
+ windows
515
+ });
516
+ if (Option.isNone(records)) return;
517
+ const record = records.value.find((candidate) => candidate.id === ref.id);
215
518
  for (const { subscriber, fields: wanted } of group) {
216
519
  if (gone.has(subscriber)) continue;
217
520
  if (record === void 0) {
@@ -224,7 +527,7 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
224
527
  continue;
225
528
  }
226
529
  const values = Object.create(null);
227
- for (const field of wanted) if (allowedSet.has(field) && Object.hasOwn(record.values, field)) values[renamed(renames, field)] = record.values[field];
530
+ for (const field of wanted) if (Object.hasOwn(record.values, field)) values[renamed(renames, field)] = record.values[field];
228
531
  const changed = Object.keys(values);
229
532
  if (changed.length === 0) continue;
230
533
  yield* emit(subscriber, {
@@ -241,11 +544,7 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
241
544
  if (failures.length > 0) return yield* Effect.fail(failures[0]);
242
545
  });
243
546
  return {
244
- subscribe: ({ requirements, after, principal, maxIdsPerEntity }) => Stream.unwrap(Effect.gen(function* () {
245
- const over = checkIdsPerEntity(requirements, Math.max(1, maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY));
246
- if (over !== void 0) return yield* new RemoteServerError({ message: `Too many "${over}" ids in one live subscription` });
247
- const paged = checkPagesPerRelation(requirements);
248
- if (paged !== void 0) return yield* new RemoteServerError({ message: `Too many pages of "${paged}" in one live subscription` });
547
+ subscribe: ({ requirements, after, principal, viewer }) => Stream.unwrap(Effect.gen(function* () {
249
548
  const selected = /* @__PURE__ */ new Map();
250
549
  for (const requirement of requirements) {
251
550
  const key = `${requirement.entity}:${requirement.id}`;
@@ -260,6 +559,7 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
260
559
  const subscriber = {
261
560
  selected,
262
561
  principal,
562
+ viewer,
263
563
  queue: yield* Queue.unbounded(),
264
564
  cursor: after
265
565
  };
@@ -511,7 +811,7 @@ function memory(config) {
511
811
  if (row === void 0 || !readable(name, row)) return [];
512
812
  return [{
513
813
  id,
514
- values: Object.fromEntries(fields.flatMap((field) => Object.hasOwn(row, field) ? [[field, valueFor(refsShown(readable, name, field, row[field]), windows?.[field])]] : []))
814
+ values: Object.fromEntries(fields.flatMap((field) => Object.hasOwn(row, field) ? [[field, valueFor(refsShown(readable, name, field, row[field]), windows !== void 0 && Object.hasOwn(windows, field) ? windows[field] : void 0)]] : []))
515
815
  }];
516
816
  }),
517
817
  catch: (error) => new RemoteServerError({ message: error instanceof Error ? error.message : String(error) })
@@ -523,13 +823,17 @@ function memory(config) {
523
823
  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\`.`);
524
824
  const queries = [...config.queries ?? [], ...[...config.domain.registry.queries.values()].filter((query) => !given.has(query.name)).map((query) => ({
525
825
  ...visible,
526
- ...RemoteServer.query(query, ({ input, window, principal }) => Effect.flatMap(readableFor(principal), (readable) => Effect.try({
826
+ ...RemoteServer.query(query, ({ input, window, principal, viewer }) => Effect.flatMap(Effect.all([readableFor(principal), Clock.currentTimeMillis]), ([readable, now]) => Effect.try({
527
827
  try: () => {
528
828
  const body = query.body;
829
+ const context = exprContext(body, viewer, now);
529
830
  const encoded = Schema.encodeSync(query.Input)(input);
530
831
  const entity = body.entity.name;
531
- const rows = store.rows(entity).filter((row) => readable(entity, row));
532
- const matched = evaluate(body, encoded, rows, { operators });
832
+ const rows = store.rows(entity).filter((row) => readable(entity, row)).map((row) => Held.fromRefs(body, row));
833
+ const matched = evaluate(body, encoded, rows, {
834
+ operators,
835
+ context
836
+ });
533
837
  const locate = (cursor) => {
534
838
  const row = rows.find((candidate) => String(candidate.id) === cursor);
535
839
  if (row === void 0) throw new Error(`Cursor "${cursor}" names a row that no longer exists`);
@@ -537,7 +841,10 @@ function memory(config) {
537
841
  index: evaluate({
538
842
  ...body,
539
843
  where: []
540
- }, encoded, [...matched, row], { operators }).indexOf(row),
844
+ }, encoded, [...matched, row], {
845
+ operators,
846
+ context
847
+ }).indexOf(row),
541
848
  exact: false
542
849
  };
543
850
  };
@@ -561,7 +868,8 @@ function memory(config) {
561
868
  const server = RemoteServer.make({
562
869
  entities: [...entities, ...config.entities ?? []],
563
870
  queries,
564
- mutations: config.mutations?.(store) ?? []
871
+ mutations: config.mutations?.(store) ?? [],
872
+ viewer: config.viewer
565
873
  });
566
874
  return {
567
875
  ...store,
@@ -569,6 +877,135 @@ function memory(config) {
569
877
  layer: Remote.clientLayer(RemoteServer.handlers(server, config.principal))
570
878
  };
571
879
  }
880
+ /** The entries of `record` whose key is in `keys`. */
881
+ const pickKeys = (record, keys) => Object.fromEntries(Object.entries(record).filter(([key]) => keys.has(key)));
882
+ /**
883
+ * A fresh read, after a mutation, of what the client shows of each row its
884
+ * outcome names: of each, the shown fields the answer left out, and every
885
+ * shown relation, since the answer's ref alone does not reach what the client
886
+ * reads of its target. Read as any read is, so `authorize` and `filter` hold.
887
+ * Only rows the read returned are answered: a row hidden from the asker keeps
888
+ * what the answer gave it rather than reading as gone.
889
+ */
890
+ const answerRead = (server, principal, options, shown, outcome) => Effect.gen(function* () {
891
+ const slices = /* @__PURE__ */ new Map();
892
+ for (const slice of shown) {
893
+ const current = slices.get(slice.entity);
894
+ slices.set(slice.entity, current === void 0 ? slice : Requirement.mergeRelation(current, slice));
895
+ }
896
+ const named = /* @__PURE__ */ new Map();
897
+ const name = (entity, id, answered) => {
898
+ const key = `${entity}:${id}`;
899
+ const row = named.get(key) ?? {
900
+ entity,
901
+ id,
902
+ answered: /* @__PURE__ */ new Set()
903
+ };
904
+ for (const field of answered) row.answered.add(field);
905
+ named.set(key, row);
906
+ };
907
+ for (const patch of outcome.entities) name(patch.entity, patch.id, Object.keys(patch.values));
908
+ for (const change of outcome.connections) if (change._tag === "Insert") name(change.edge.entity, change.edge.id, []);
909
+ for (const row of outcome.pointed ?? []) name(row.entity, row.id, []);
910
+ for (const gone of outcome.deleted) named.delete(`${gone.entity}:${gone.id}`);
911
+ const requests = [];
912
+ for (const row of named.values()) {
913
+ const slice = slices.get(row.entity);
914
+ if (slice === void 0) continue;
915
+ const relations = slice.relations ?? {};
916
+ const fields = slice.fields.filter((field) => !row.answered.has(field) || Object.hasOwn(relations, field));
917
+ const kept = new Set(fields);
918
+ requests.push({
919
+ entity: row.entity,
920
+ id: row.id,
921
+ fields,
922
+ ...slice.windows === void 0 ? {} : { windows: pickKeys(slice.windows, kept) },
923
+ ...slice.relations === void 0 ? {} : { relations: pickKeys(slice.relations, kept) }
924
+ });
925
+ }
926
+ const read = yield* RemoteServer.readHelper(server, principal, options, requests);
927
+ const reached = new Set(read.entities.map((row) => `${row.entity}:${row.id}`));
928
+ const found = requests.filter((request) => reached.has(`${request.entity}:${request.id}`));
929
+ const unreached = new Set(requests.map((request) => `${request.entity}:${request.id}`).filter((key) => !reached.has(key)));
930
+ const result = {
931
+ entities: read.entities,
932
+ settled: read.settled.filter((row) => !unreached.has(`${row.entity}:${row.id}`))
933
+ };
934
+ return found.length === 0 ? Option.none() : Option.some({
935
+ requests: found,
936
+ result
937
+ });
938
+ });
939
+ /**
940
+ * A query's page as `FoldkitRemoteQuery` answers it: the source's edges, and
941
+ * with a select, what the page's items select, read through `readHelper`, so
942
+ * `authorize` and `filter` hold. A mutation's answer reads its lists with it.
943
+ */
944
+ const answerQuery = (server, caller, options, payload) => Effect.gen(function* () {
945
+ const source = server.queries.get(payload.query);
946
+ if (source === void 0) return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` });
947
+ const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteQueryError({ message: "Invalid query input" }))));
948
+ const select = payload.select;
949
+ if (select !== void 0) {
950
+ const paged = checkPagesPerRelation([select]);
951
+ if (paged !== void 0) return yield* new RemoteQueryError({ message: `Too many pages of "${paged}" in one query select` });
952
+ }
953
+ const page = yield* source.run({
954
+ input,
955
+ window: payload.window,
956
+ principal: caller,
957
+ viewer: viewerOf(server, caller),
958
+ ...select === void 0 ? {} : { select }
959
+ }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
960
+ if (select === void 0) return {
961
+ edges: page.edges,
962
+ start: page.start,
963
+ end: page.end
964
+ };
965
+ const requirements = page.edges.flatMap((edge) => edge.entity === select.entity ? [{
966
+ entity: select.entity,
967
+ id: edge.id,
968
+ fields: [...select.fields],
969
+ ...select.windows === void 0 ? {} : { windows: select.windows },
970
+ ...select.relations === void 0 ? {} : { relations: select.relations }
971
+ }] : []);
972
+ if (requirements.length === 0) return {
973
+ edges: page.edges,
974
+ start: page.start,
975
+ end: page.end,
976
+ entities: [],
977
+ settled: []
978
+ };
979
+ const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(Effect.catchTag("RemoteReadError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
980
+ return {
981
+ edges: page.edges,
982
+ start: page.start,
983
+ end: page.end,
984
+ ...read
985
+ };
986
+ });
987
+ /**
988
+ * The lists of a mutation request the server answers after the write, judged
989
+ * before it runs: each a first page (`first`, no `after`) of a query it serves,
990
+ * selecting that query's entity, within the select's page bound, while the
991
+ * rows every admitted list may return stay within `maxIds` per entity. One
992
+ * past these is not answered, and the client asks for it again; the write
993
+ * runs either way.
994
+ */
995
+ const admitLists = (server, lists, maxIds) => {
996
+ const rows = /* @__PURE__ */ new Map();
997
+ return lists.filter((request) => {
998
+ const source = server.queries.get(request.query);
999
+ const { select, window } = request;
1000
+ if (source === void 0 || select === void 0 || select.entity !== source.entity) return false;
1001
+ if (window.first === void 0 || window.after !== void 0) return false;
1002
+ if (checkPagesPerRelation([select]) !== void 0) return false;
1003
+ const listed = (rows.get(select.entity) ?? 0) + window.first;
1004
+ if (listed > maxIds) return false;
1005
+ rows.set(select.entity, listed);
1006
+ return true;
1007
+ });
1008
+ };
572
1009
  /**
573
1010
  * A Source's refusal as the client receives it: encoded by the mutation's own
574
1011
  * `Refusal`. A refusal made for another mutation, or one the mutation does not
@@ -621,7 +1058,8 @@ const RemoteServer = {
621
1058
  input: context.input,
622
1059
  principal: context.principal,
623
1060
  requestId: context.requestId,
624
- operation: context.operation
1061
+ operation: context.operation,
1062
+ now: context.now
625
1063
  }).pipe(Effect.map((outcome) => ({
626
1064
  output: outcome.output,
627
1065
  entities: outcome.entities ?? [],
@@ -647,6 +1085,12 @@ const RemoteServer = {
647
1085
  */
648
1086
  unmet: (message = "The row does not hold what the write asks of it") => new RemoteUnmet({ message }),
649
1087
  /**
1088
+ * A writer's refusal of an insert whose id a row already holds: fail
1089
+ * `insert` with it (`yield* RemoteServer.taken()`), and `RemoteServer.write`
1090
+ * answers the mutation's `Taken` refusal, naming the Entity and the id.
1091
+ */
1092
+ taken: (message = "The id is already taken") => new RemoteTaken({ message }),
1093
+ /**
650
1094
  * A writer's refusal of a row that would break an invariant: fail `update`
651
1095
  * or `insert` with it, naming the invariant's id and path when the caller
652
1096
  * may be told them, and `RemoteServer.write` answers the mutation's
@@ -671,8 +1115,10 @@ const RemoteServer = {
671
1115
  /**
672
1116
  * A refusal of a caller who could not be told: a `serveFetch` or
673
1117
  * `defineDocumentHost` resolver fails with it (`RemoteServer.unauthenticated()`)
674
- * when the credential it was sent no longer holds. It answers 401, with
675
- * `reason`, when given, for the person who asked.
1118
+ * when the credential it was sent no longer holds, and a write refused to a
1119
+ * visitor fails with it (`GuardServer` does), so a client can tell a session
1120
+ * that ended from a refusal. It answers 401, with `reason`, when given, for
1121
+ * the person who asked; a durable write so answered waits for a sign-in.
676
1122
  */
677
1123
  unauthenticated: (reason) => new RemoteUnauthenticated({
678
1124
  message: reason ?? "Unauthenticated",
@@ -683,8 +1129,9 @@ const RemoteServer = {
683
1129
  * input bound to the write lands through `writer`, and the row as written
684
1130
  * answers as a patch (a deletion as `deleted`). An update writes only the
685
1131
  * keys the client named, when it named some, and fails for a row that is not
686
- * there; an insert of an id already holding what it writes (a retry)
687
- * answers with that row, and of one holding anything else fails; a delete of
1132
+ * there; an insert of an id already taken is refused as taken, alike
1133
+ * whatever the row holds, unless the writer's ledger records this operation
1134
+ * as the insert that made it (a retry), answered with that row; a delete of
688
1135
  * a row already gone succeeds. A row that moved past the revision the write
689
1136
  * `expect`s is refused as a conflict, and one that does not hold its `when`
690
1137
  * as unmet; a write with a `when` needs a writer that checks it
@@ -705,15 +1152,86 @@ const RemoteServer = {
705
1152
  }
706
1153
  const refused = writer.refuses?.(write) ?? [];
707
1154
  if (refused.length > 0) throw new Error(`[foldkit-remote-server] write "${mutation.name}" cannot land through its writer for ${writer.entity}: ${refused.join("; ")}`);
708
- const judged = Entity.invariants(write.input.entity).filter((held) => write._tag === "Update" || !Entity.readsBefore(held));
1155
+ const kind = Match.value(write).pipe(Match.tagsExhaustive({
1156
+ Insert: () => ({
1157
+ hasBefore: false,
1158
+ inserts: true,
1159
+ deletes: false
1160
+ }),
1161
+ Update: () => ({
1162
+ hasBefore: true,
1163
+ inserts: false,
1164
+ deletes: false
1165
+ }),
1166
+ Delete: () => ({
1167
+ hasBefore: false,
1168
+ inserts: false,
1169
+ deletes: true
1170
+ })
1171
+ }));
1172
+ const judged = Entity.invariants(write.input.entity).filter((held) => kind.hasBefore || !Entity.readsBefore(held));
709
1173
  if (judged.length > 0 && writer.invariants !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" writes ${writer.entity}, which has invariants, but its writer does not judge them (invariants)`);
710
- if (write._tag === "Insert") {
711
- const sets = /* @__PURE__ */ new Set(["id", ...write.sets.map((set) => set.field.key)]);
1174
+ if (kind.inserts) {
1175
+ const sets = /* @__PURE__ */ new Set([
1176
+ "id",
1177
+ ...write.sets.map((set) => set.field.key),
1178
+ ...write.links.map((link) => link.relation.key),
1179
+ ...write.context.map(({ member }) => member.key)
1180
+ ]);
712
1181
  const unset = judged.flatMap((held) => held.after.filter((key) => !sets.has(key)).map((key) => `${held.id} reads ${key}`));
713
1182
  if (unset.length > 0) throw new Error(`[foldkit-remote-server] insert "${mutation.name}" leaves unset a field an invariant reads (${unset.join("; ")})`);
714
1183
  }
715
1184
  if (Option.isSome(write.when) && writer.preconditions !== true) throw new Error(`[foldkit-remote-server] write "${mutation.name}" has a precondition, but its writer for ${writer.entity} does not check one (preconditions)`);
716
1185
  const encodeInput = Schema.encodeUnknownEffect(write.input.schema);
1186
+ const pointersOf = (entity) => {
1187
+ const relations = entity.relations;
1188
+ return Object.values(relations).flatMap((relation) => {
1189
+ if (relation._tag !== "Relation" || relation.cardinality !== "one") return [];
1190
+ const isThis = (read) => read.owner.token === relation.owner.token && read.key === relation.key;
1191
+ return Object.values(relation.target().derived).some((member) => member._tag === "Derived" && Derivation.$match(member.derives, {
1192
+ Supplied: () => true,
1193
+ Count: ({ relation: read }) => isThis(read),
1194
+ Exists: ({ relation: read }) => isThis(read)
1195
+ })) ? [relation.key] : [];
1196
+ });
1197
+ };
1198
+ const pointers = pointersOf(write.input.entity);
1199
+ const cascadePointers = /* @__PURE__ */ new Map();
1200
+ if (kind.deletes) {
1201
+ const reach = (entity) => {
1202
+ for (const { owner } of Entity.cascading(entity)) {
1203
+ if (cascadePointers.has(owner.name)) continue;
1204
+ cascadePointers.set(owner.name, pointersOf(owner));
1205
+ reach(owner);
1206
+ }
1207
+ };
1208
+ reach(write.input.entity);
1209
+ if (cascadePointers.size > 0 && writer.cascades !== true) throw new Error(`[foldkit-remote-server] delete "${mutation.name}" removes ${write.input.entity.name}, whose rows take ${[...cascadePointers.keys()].join(", ")} with them (onDelete: 'cascade'), but its writer does not remove them (cascades)`);
1210
+ }
1211
+ /** What a removed row pointed at that its removal moves, as refs. */
1212
+ const pointedBy = (row) => (cascadePointers.get(row.entity) ?? []).flatMap((key) => Option.match(Option.flatten(Option.fromUndefinedOr(row.links[key])), {
1213
+ onNone: () => [],
1214
+ onSome: (ref) => [ref]
1215
+ }));
1216
+ const seenLinks = (id, principal) => writer.read !== void 0 ? writer.read({
1217
+ id,
1218
+ fields: pointers,
1219
+ principal
1220
+ }) : writer.linked !== void 0 ? writer.linked({
1221
+ id,
1222
+ relations: pointers
1223
+ }) : Effect.succeed(Option.none());
1224
+ const pointedAt = (id, principal) => pointers.length === 0 ? Effect.succeed([]) : Effect.map(seenLinks(id, principal), (held) => Option.match(held, {
1225
+ onNone: () => [],
1226
+ onSome: (links) => pointers.flatMap((key) => {
1227
+ const ref = Object.hasOwn(links, key) ? links[key] : void 0;
1228
+ return typeof ref === "string" ? [refParts(ref)] : [];
1229
+ })
1230
+ }));
1231
+ const naming = (outcome, pointed) => pointed.length === 0 ? outcome : {
1232
+ ...outcome,
1233
+ pointed
1234
+ };
717
1235
  return {
718
1236
  mutation: mutation.name,
719
1237
  writes: {
@@ -724,7 +1242,16 @@ const RemoteServer = {
724
1242
  Input: mutation.Input,
725
1243
  Output: mutation.Output,
726
1244
  Refusal: mutation.Refusal,
727
- run: ({ input, principal, keys, operation }) => {
1245
+ run: ({ input, principal, viewer, keys, operation, now, read }) => {
1246
+ /** A path from the viewer, read through the server's sources: a row hidden or gone is null. */
1247
+ const context = Write.contextValues(write, {
1248
+ viewer,
1249
+ now: Option.some(now)
1250
+ }, (row, key) => Effect.map(read(row, [key]), (found) => Held.of(Option.match(found, {
1251
+ onNone: () => null,
1252
+ onSome: (values) => Object.hasOwn(values, key) ? values[key] : void 0
1253
+ }))));
1254
+ const unfilled = Option.isNone(viewer) ? RemoteServer.unauthenticated() : RemoteServer.forbid();
728
1255
  const given = input;
729
1256
  const expect = Write.expected(write, given);
730
1257
  const conflict = (bound) => RemoteServer.refuse(mutation, { _tag: "Conflict" }, `${bound.entity} ${bound.id} changed since it was read`);
@@ -738,6 +1265,7 @@ const RemoteServer = {
738
1265
  const unmet = (bound, writing) => Effect.catchTag(writing, "RemoteUnmet", () => Option.isNone(write.when) ? Effect.fail(new RemoteServerError({ message: `${writer.entity}'s writer refused ${mutation.name}, which has no precondition, as unmet` })) : Effect.fail(RemoteServer.refuse(mutation, { _tag: "Unmet" }, `${bound.entity} ${bound.id} does not hold what ${mutation.name} asks of it`)));
739
1266
  const invalid = (writing) => Effect.catchTag(writing, "RemoteInvalid", (refused) => Effect.fail(RemoteServer.refuse(mutation, {
740
1267
  _tag: "Invalid",
1268
+ entity: Option.some(write.input.entity.name),
741
1269
  rule: refused.rule,
742
1270
  message: refused.message,
743
1271
  path: refused.path
@@ -771,13 +1299,33 @@ const RemoteServer = {
771
1299
  })
772
1300
  }));
773
1301
  };
1302
+ const request = encodeInput(given).pipe(Effect.map((encoded) => JSON.stringify([
1303
+ mutation.name,
1304
+ keys ?? null,
1305
+ encoded
1306
+ ])), Effect.mapError(() => new RemoteServerError({ message: `${mutation.name}'s input did not encode` })));
774
1307
  return Match.value(write).pipe(Match.tagsExhaustive({
775
1308
  Update: () => Effect.gen(function* () {
776
- const bound = Write.bind(write, given, keys);
1309
+ const named = Write.bind(write, given, keys);
1310
+ const set = yield* context;
1311
+ if (set.unfilled.length > 0) return yield* Effect.fail(unfilled);
1312
+ const bound = {
1313
+ ...named,
1314
+ values: {
1315
+ ...named.values,
1316
+ ...set.values
1317
+ },
1318
+ links: {
1319
+ ...named.links,
1320
+ ...set.links
1321
+ }
1322
+ };
1323
+ const before = yield* pointedAt(bound.id, principal);
777
1324
  if (write.increments.length + write.assignments.length > 0 && write.expect === void 0 && Option.isNone(operation)) return yield* new RemoteServerError({ message: `${mutation.name} moves a field with no revision, so it needs an operation id` });
778
1325
  const written = yield* invalid(unmet(bound, writer.update({
779
1326
  id: bound.id,
780
1327
  operation,
1328
+ request: yield* request,
781
1329
  values: bound.values,
782
1330
  increments: bound.increments,
783
1331
  assignments: bound.assignments,
@@ -786,36 +1334,59 @@ const RemoteServer = {
786
1334
  when: yield* when,
787
1335
  principal
788
1336
  })));
789
- if (Option.isSome(written)) return yield* answered(bound, written.value);
1337
+ if (Option.isSome(written)) return naming(yield* answered(bound, written.value), [...before, ...yield* pointedAt(bound.id, principal)]);
790
1338
  return yield* Option.isSome(expect) ? Effect.fail(conflict(bound)) : Effect.fail(new RemoteServerError({ message: `No ${bound.entity} ${bound.id} to update` }));
791
1339
  }),
792
1340
  Insert: () => Effect.gen(function* () {
793
1341
  const bound = Write.bind(write, given);
1342
+ const set = yield* context;
1343
+ if (set.unfilled.length > 0) return yield* Effect.fail(unfilled);
794
1344
  const row = yield* invalid(writer.insert({
795
1345
  id: bound.id,
796
- values: bound.values,
797
- links: bound.links,
1346
+ values: {
1347
+ ...bound.values,
1348
+ ...set.values
1349
+ },
1350
+ links: {
1351
+ ...bound.links,
1352
+ ...set.links
1353
+ },
1354
+ operation,
1355
+ request: yield* request,
798
1356
  principal
799
- }));
800
- return yield* answered(bound, row);
1357
+ }).pipe(Effect.catchTag("RemoteTaken", () => Effect.fail(RemoteServer.refuse(mutation, {
1358
+ _tag: "Taken",
1359
+ entity: bound.entity,
1360
+ id: bound.id
1361
+ }, `${bound.entity} ${bound.id} is already taken`)))));
1362
+ return naming(yield* answered(bound, row), yield* pointedAt(bound.id, principal));
801
1363
  }),
802
1364
  Delete: () => Effect.gen(function* () {
803
1365
  const bound = Write.bind(write, given);
804
- if ((yield* invalid(unmet(bound, writer.delete({
1366
+ const before = yield* pointedAt(bound.id, principal);
1367
+ const outcome = yield* invalid(unmet(bound, writer.delete({
805
1368
  id: bound.id,
806
1369
  expect,
807
1370
  when: yield* when,
808
1371
  principal
809
- })))) === "moved") return yield* Effect.fail(conflict(bound));
810
- return {
1372
+ })));
1373
+ const gone = (cascaded) => ({
811
1374
  output: {},
812
1375
  entities: [],
813
1376
  connections: [],
814
1377
  deleted: [{
815
1378
  entity: bound.entity,
816
1379
  id: bound.id
817
- }]
818
- };
1380
+ }, ...cascaded.map(({ entity, id }) => ({
1381
+ entity,
1382
+ id
1383
+ }))]
1384
+ });
1385
+ return yield* DeleteOutcome.$match(outcome, {
1386
+ Moved: () => Effect.fail(conflict(bound)),
1387
+ Absent: () => Effect.succeed(gone([])),
1388
+ Deleted: ({ cascaded }) => Effect.succeed(naming(gone(cascaded), [...before, ...cascaded.flatMap(pointedBy)]))
1389
+ });
819
1390
  })
820
1391
  }));
821
1392
  }
@@ -823,14 +1394,30 @@ const RemoteServer = {
823
1394
  },
824
1395
  query: (query, run) => ({
825
1396
  query: query.name,
1397
+ entity: query.Result.entity,
826
1398
  Input: query.Input,
827
1399
  run: (context) => run({
828
1400
  input: context.input,
829
1401
  window: context.window,
830
1402
  principal: context.principal,
1403
+ viewer: context.viewer,
831
1404
  ...context.select === void 0 ? {} : { select: context.select }
832
1405
  })
833
1406
  }),
1407
+ /**
1408
+ * Reads through `source` as the read handlers and the live hub do: only the
1409
+ * asked fields the source declares and its `authorize` allows, each record
1410
+ * through its `filter` and holding no other field. None when the principal
1411
+ * may read none of the fields asked. What a live source of its own reads
1412
+ * with, so it sends no more than a read would.
1413
+ */
1414
+ readAs,
1415
+ /**
1416
+ * The fields of `fields` that `readAs` reads for `principal`: those the
1417
+ * source declares and its `authorize` allows, in the order asked. Asks
1418
+ * nothing of the store.
1419
+ */
1420
+ allowedFields,
834
1421
  /** Streams live entity patches for a client's live requirements. */
835
1422
  live: (entity, options) => ({
836
1423
  entity: entity.name,
@@ -845,12 +1432,44 @@ const RemoteServer = {
845
1432
  * own principal.
846
1433
  */
847
1434
  liveHub,
848
- make: (config) => ({
849
- entities: new Map(config.entities.map((source) => [source.entity, source])),
850
- mutations: new Map((config.mutations ?? []).map((source) => [source.mutation, source])),
851
- queries: new Map((config.queries ?? []).map((source) => [source.query, source])),
852
- live: new Map((config.live ?? []).map((source) => [source.entity, source]))
853
- }),
1435
+ /**
1436
+ * The server: its sources by name. `viewer` says who asks, as a row
1437
+ * (`principal => Option.some(Remote.ref(User, principal.id))`), or none for
1438
+ * a visitor: what a declared write's `Expr.viewer` sets. A server
1439
+ * registering such an insert without one is refused here. It is also whom
1440
+ * each answer says it is for (`principal`, the row's key), which a durable
1441
+ * write carries back: one made for another viewer than who asks is refused
1442
+ * before it runs (`RemotePrincipalChanged`). A server without `viewer`
1443
+ * names no one in its answers, and refuses a write that names someone,
1444
+ * since it cannot check it; a write that names no one runs (#405).
1445
+ *
1446
+ * `clockSkew` is how far from this server's clock a client's time (the
1447
+ * `now` a write is sent with, when the reader acted) may be and still be
1448
+ * the write's time: 60 seconds unless given, and `0` to never take it. A
1449
+ * time beyond it is replaced by the server's own, and reported as
1450
+ * `ClockSkewed`. It bounds how far a client can backdate or postdate a row.
1451
+ */
1452
+ make: (config) => {
1453
+ const served = new Set(config.entities.map((source) => source.entity));
1454
+ for (const source of config.mutations ?? []) {
1455
+ const unserved = (source.writes === void 0 ? [] : Write.contextReads(source.writes.write)).filter((entity) => !served.has(entity));
1456
+ if (unserved.length > 0) throw new Error(`[foldkit-remote-server] write "${source.mutation}" sets a member from a path through ${unserved.join(", ")}, which no source of this server serves; mount one in entities`);
1457
+ }
1458
+ if (config.viewer === void 0) {
1459
+ const viewing = (config.mutations ?? []).find((source) => (source.writes?.write.context ?? []).some(({ value }) => value._tag === "Viewer"));
1460
+ if (viewing !== void 0) throw new Error(`[foldkit-remote-server] write "${viewing.mutation}" sets a member to whoever asks (Expr.viewer), but the server has no viewer; give RemoteServer.make a viewer`);
1461
+ const reading = config.entities.find((source) => (source.perViewer ?? []).length > 0);
1462
+ if (reading !== void 0) throw new Error(`[foldkit-remote-server] ${reading.entity}'s ${reading.perViewer.join(", ")} depend on who reads them (Derived.exists), but the server has no viewer; give RemoteServer.make a viewer`);
1463
+ }
1464
+ return {
1465
+ entities: new Map(config.entities.map((source) => [source.entity, source])),
1466
+ mutations: new Map((config.mutations ?? []).map((source) => [source.mutation, source])),
1467
+ queries: new Map((config.queries ?? []).map((source) => [source.query, source])),
1468
+ live: new Map((config.live ?? []).map((source) => [source.entity, source])),
1469
+ viewer: config.viewer,
1470
+ ...config.clockSkew === void 0 ? {} : { clockSkew: Duration.fromInputUnsafe(config.clockSkew) }
1471
+ };
1472
+ },
854
1473
  /**
855
1474
  * Checks every source name against the declared domain, so an undeclared
856
1475
  * entity/query/mutation fails at startup rather than returning nothing at
@@ -886,6 +1505,7 @@ const RemoteServer = {
886
1505
  };
887
1506
  const fetched = /* @__PURE__ */ new Map();
888
1507
  const fetchedValues = /* @__PURE__ */ new Map();
1508
+ const viewer = viewerOf(server, principal);
889
1509
  const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
890
1510
  const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY);
891
1511
  const over = checkIdsPerEntity(requests, maxIds);
@@ -929,6 +1549,7 @@ const RemoteServer = {
929
1549
  ids: chunk,
930
1550
  fields,
931
1551
  principal,
1552
+ viewer,
932
1553
  ...windows
933
1554
  })), (chunks) => chunks.flat())).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteReadError({ message: error.message }))));
934
1555
  for (const record of records) {
@@ -977,8 +1598,11 @@ const RemoteServer = {
977
1598
  * The request and its payload are decoded by the protocol's own schemas
978
1599
  * before a handler sees them, so an operation name is one of Remote's three
979
1600
  * and nothing else. A body that is not a request is a 400; a caller who
980
- * could not be told a 401; a refusal of who is asking a 403; a handler's
981
- * failure a 500 with its message; a defect a 500 that says nothing of it.
1601
+ * could not be told a 401; a refusal of who is asking a 403; a write made
1602
+ * for someone else (`RemotePrincipalChanged`) a 409; a mutation's
1603
+ * declared refusal a 422, or a 409 when it is `Refusal.taken`; a handler's
1604
+ * failure a 500 with its message; a defect a 500 that says nothing of it,
1605
+ * its cause reported as a `ServerDefect` (`Diagnostics`, by default the log).
982
1606
  * `Remote.json` and `Remote.http` are the other end.
983
1607
  */
984
1608
  answer: (handlers, body) => {
@@ -993,7 +1617,13 @@ const RemoteServer = {
993
1617
  })), Effect.catchTag("SchemaError", (error) => Effect.succeed({
994
1618
  status: 400,
995
1619
  body: { error: error.message }
996
- })), Effect.catchTag("Unauthenticated", (error) => Effect.succeed(unauthenticatedAnswer(error))), Effect.catchTag("Forbidden", (error) => Effect.succeed({
1620
+ })), Effect.catchTag("Unauthenticated", (error) => Effect.succeed(unauthenticatedAnswer(error))), Effect.catchTag("PrincipalChanged", (error) => Effect.succeed({
1621
+ status: 409,
1622
+ body: {
1623
+ error: error.message,
1624
+ principalChanged: {}
1625
+ }
1626
+ })), Effect.catchTag("Forbidden", (error) => Effect.succeed({
997
1627
  status: 403,
998
1628
  body: {
999
1629
  error: error.message,
@@ -1003,7 +1633,7 @@ const RemoteServer = {
1003
1633
  status: 500,
1004
1634
  body: { error: error.message }
1005
1635
  } : {
1006
- status: 422,
1636
+ status: Refusal.isTaken(error.refusal) ? 409 : 422,
1007
1637
  body: {
1008
1638
  error: error.message,
1009
1639
  refusal: error.refusal
@@ -1011,10 +1641,10 @@ const RemoteServer = {
1011
1641
  })), Effect.catch((error) => Effect.succeed({
1012
1642
  status: 500,
1013
1643
  body: { error: error.message }
1014
- })), Effect.catchCause(() => Effect.succeed({
1644
+ })), Effect.catchCause((cause) => Diagnostics.report(serverDefect(cause)).pipe(Effect.as({
1015
1645
  status: 500,
1016
1646
  body: { error: "Internal error" }
1017
- })));
1647
+ }))));
1018
1648
  },
1019
1649
  /**
1020
1650
  * Compiles the server into Remote's RPC handlers, answering as `principal`:
@@ -1030,28 +1660,41 @@ const RemoteServer = {
1030
1660
  const mismatch = protocolMismatch(payload.version);
1031
1661
  if (mismatch !== void 0) return yield* mismatch;
1032
1662
  const caller = yield* asking;
1033
- return yield* RemoteServer.readHelper(server, caller, options, payload.requests);
1663
+ return {
1664
+ ...yield* RemoteServer.readHelper(server, caller, options, payload.requests),
1665
+ ...answeredFor(server, caller)
1666
+ };
1034
1667
  }),
1035
1668
  FoldkitRemoteMutate: Effect.fn("RemoteServer.FoldkitRemoteMutate")(function* (payload) {
1036
1669
  const source = server.mutations.get(payload.mutation);
1037
1670
  if (source === void 0) return yield* new RemoteMutationError({ message: `Unknown mutation: ${payload.mutation}` });
1038
1671
  const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation input" }))));
1672
+ const lists = admitLists(server, payload.lists ?? [], Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY));
1039
1673
  const caller = yield* asking;
1674
+ yield* madeFor(server, caller, Option.fromUndefinedOr(payload.principal));
1040
1675
  const outcome = yield* source.run({
1041
1676
  input,
1042
1677
  principal: caller,
1678
+ viewer: server.viewer === void 0 ? Option.none() : server.viewer(caller),
1043
1679
  requestId: payload.requestId,
1044
1680
  operation: Option.fromUndefinedOr(payload.operation),
1681
+ now: yield* writeTime(server, payload.mutation, Option.fromUndefinedOr(payload.now)),
1682
+ read: withServices(rowAs(server, caller), yield* Effect.context()),
1045
1683
  keys: payload.keys
1046
1684
  }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteMutationError({ message: error.message }))), Effect.catchTag("MutationRefused", (refused) => refusalError(source.Refusal, payload.mutation, refused)));
1047
1685
  const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation output" }))));
1686
+ const read = yield* answerRead(server, caller, options, payload.shown ?? [], outcome).pipe(Effect.catchTag("RemoteReadError", (error) => Diagnostics.report(answerUnread(payload.mutation, error.message)).pipe(Effect.as(Option.none()))));
1687
+ const answered = yield* Effect.forEach(lists, (request) => answerQuery(server, caller, options, request).pipe(Effect.map((result) => [{
1688
+ request,
1689
+ result
1690
+ }]), Effect.catchTag("RemoteQueryError", (error) => Diagnostics.report(answerUnread(payload.mutation, `list "${request.query}": ${error.message}`)).pipe(Effect.as([]))))).pipe(Effect.map((pages) => pages.flat()));
1048
1691
  const hub = options.live;
1049
1692
  if (hub !== void 0) {
1050
1693
  const stored = source.writes !== void 0;
1051
1694
  yield* Effect.forEach(outcome.entities, (patch) => hub.changed({
1052
1695
  entity: patch.entity,
1053
1696
  id: patch.id
1054
- }, Object.keys(patch.values), stored ? patch.values : void 0)).pipe(Effect.andThen(Effect.forEach(outcome.deleted, (gone) => hub.deleted(gone))), Effect.catchCause((cause) => Effect.logWarning("RemoteServer: a mutation committed but its live publish failed", cause)));
1697
+ }, Object.keys(patch.values), stored ? patch.values : void 0)).pipe(Effect.andThen(Effect.forEach(outcome.deleted, (gone) => hub.deleted(gone))), Effect.catchCause((cause) => Diagnostics.report(publishFailed(payload.mutation, cause))));
1055
1698
  }
1056
1699
  return {
1057
1700
  output,
@@ -1064,77 +1707,69 @@ const RemoteServer = {
1064
1707
  deleted: outcome.deleted.map((gone) => ({
1065
1708
  entity: gone.entity,
1066
1709
  id: gone.id
1067
- }))
1710
+ })),
1711
+ ...Option.match(read, {
1712
+ onNone: () => ({}),
1713
+ onSome: (value) => ({ read: value })
1714
+ }),
1715
+ ...answered.length === 0 ? {} : { lists: answered },
1716
+ ...answeredFor(server, caller)
1068
1717
  };
1069
1718
  }),
1070
1719
  FoldkitRemoteQuery: Effect.fn("RemoteServer.FoldkitRemoteQuery")(function* (payload) {
1071
- const source = server.queries.get(payload.query);
1072
- if (source === void 0) return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` });
1073
- const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteQueryError({ message: "Invalid query input" }))));
1074
- const select = payload.select;
1075
- if (select !== void 0) {
1076
- const paged = checkPagesPerRelation([select]);
1077
- if (paged !== void 0) return yield* new RemoteQueryError({ message: `Too many pages of "${paged}" in one query select` });
1078
- }
1079
1720
  const caller = yield* asking;
1080
- const page = yield* source.run({
1081
- input,
1082
- window: payload.window,
1083
- principal: caller,
1084
- ...select === void 0 ? {} : { select }
1085
- }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
1086
- if (select === void 0) return {
1087
- edges: page.edges,
1088
- start: page.start,
1089
- end: page.end
1090
- };
1091
- const requirements = page.edges.flatMap((edge) => edge.entity === select.entity ? [{
1092
- entity: select.entity,
1093
- id: edge.id,
1094
- fields: [...select.fields],
1095
- ...select.windows === void 0 ? {} : { windows: select.windows },
1096
- ...select.relations === void 0 ? {} : { relations: select.relations }
1097
- }] : []);
1098
- if (requirements.length === 0) return {
1099
- edges: page.edges,
1100
- start: page.start,
1101
- end: page.end,
1102
- entities: [],
1103
- settled: []
1104
- };
1105
- const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(Effect.catchTag("RemoteReadError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
1106
1721
  return {
1107
- edges: page.edges,
1108
- start: page.start,
1109
- end: page.end,
1110
- ...read
1722
+ ...yield* answerQuery(server, caller, options, payload),
1723
+ ...answeredFor(server, caller)
1111
1724
  };
1112
1725
  }),
1113
1726
  FoldkitRemoteLive: (payload) => {
1114
1727
  const mismatch = protocolMismatch(payload.version);
1115
1728
  if (mismatch !== void 0) return Stream.fail(mismatch);
1116
- return Stream.unwrap(Effect.map(asking, (caller) => {
1117
- const streams = [...new Set(payload.requirements.map((request) => request.entity))].flatMap((entity) => {
1729
+ const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY);
1730
+ const refusal = liveRefusal(payload.requirements, maxIds);
1731
+ if (refusal !== void 0) return Stream.fail(refusal);
1732
+ return Stream.unwrap(Effect.gen(function* () {
1733
+ const admitted = yield* admitQueries(server, payload.queries ?? [], payload.requirements, maxIds);
1734
+ const caller = yield* asking;
1735
+ const viewer = viewerOf(server, caller);
1736
+ const queries = admitted.map(({ request, select, source, input }) => ({
1737
+ identity: queryIdentity(request.query, request.input),
1738
+ select,
1739
+ edges: Effect.map(source.run({
1740
+ input,
1741
+ window: request.window,
1742
+ principal: caller,
1743
+ viewer,
1744
+ select
1745
+ }), (page) => page.edges)
1746
+ }));
1747
+ const streams = [.../* @__PURE__ */ new Set([...payload.requirements.map((request) => request.entity), ...queries.map((query) => query.select.entity)])].flatMap((entity) => {
1118
1748
  const source = server.live.get(entity);
1119
1749
  if (source === void 0) return [];
1120
1750
  return [source.subscribe({
1121
1751
  requirements: payload.requirements.filter((request) => request.entity === entity),
1752
+ queries: queries.filter((query) => query.select.entity === entity),
1122
1753
  after: payload.after,
1123
- principal: caller
1754
+ principal: caller,
1755
+ viewer
1124
1756
  })];
1125
1757
  });
1126
1758
  if (options.live !== void 0) streams.push(options.live.subscribe({
1127
1759
  requirements: payload.requirements,
1128
1760
  after: payload.after,
1129
1761
  principal: caller,
1130
- maxIdsPerEntity: options.maxIdsPerEntity
1762
+ viewer
1131
1763
  }));
1132
- return Stream.mergeAll(streams, { concurrency: "unbounded" }).pipe(Stream.mapError((error) => new RemoteLiveError({ message: error.message })));
1764
+ return Stream.mergeAll(streams, { concurrency: "unbounded" }).pipe(Stream.mapAccum(() => payload.after, (cursor, change) => [cursor + 1, [{
1765
+ ...change,
1766
+ cursor: cursor + 1
1767
+ }]]), Stream.mapError((error) => new RemoteLiveError({ message: error.message })));
1133
1768
  }));
1134
1769
  }
1135
1770
  };
1136
1771
  }
1137
1772
  };
1138
- export { RemoteUnmet as a, evaluate$1 as c, RemoteServerError as i, supported as l, RemoteInvalid as n, QueryEvaluateError as o, RemoteServer as r, assertSupported$1 as s, MutationRefused as t, unauthenticatedAnswer as u };
1773
+ export { supported as _, RemoteServerError as a, RowRequirement as c, declaresTooLarge as d, readJson as f, evaluate$1 as g, assertSupported$1 as h, RemoteServer as i, exprContext as l, QueryEvaluateError as m, MutationRefused as n, RemoteTaken as o, tooLargeAnswer as p, RemoteInvalid as r, RemoteUnmet as s, DeleteOutcome as t, bodyLimit as u, unauthenticatedAnswer as v, serverDefect as y };
1139
1774
 
1140
- //# sourceMappingURL=src-yDMwdGiL.mjs.map
1775
+ //# sourceMappingURL=src-D8azLxgd.mjs.map