foldkit-remote-server 0.18.0 → 0.19.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,45 @@
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 { Diagnostics, MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Refusal, Remote, RemoteForbidden, RemoteJsonRequest, RemoteLiveError, RemoteLiveRefused, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, RemoteUnauthenticated, Requirement, aliasedField, connectionIdentity, entityKey, queryIdentity, refParts, refsIn, relationShape, stableStringify } from "foldkit-remote";
4
+ // src/diagnostics.ts
5
+ /**
6
+ * What a Remote server answers past without telling the caller why: a defect
7
+ * it answered "Internal error", a committed mutation whose answer's read or
8
+ * live publish failed, and a client's time it would not take. Each is
9
+ * reported through `Diagnostics.report`, so a host's log (a Worker's
10
+ * `wrangler tail`) shows it by default.
11
+ */
12
+ const source = "foldkit-remote-server";
13
+ const serverDefect = (cause) => ({
14
+ _tag: "ServerDefect",
15
+ source,
16
+ level: "error",
17
+ message: `a request failed on this side, and its caller was answered "Internal error"\n${Cause.pretty(cause)}`,
18
+ cause
19
+ });
20
+ const answerUnread = (mutation, reason) => ({
21
+ _tag: "AnswerUnread",
22
+ source,
23
+ level: "warning",
24
+ message: `${mutation} committed, but reading its answer failed (${reason}): the client reads the rows it names again.`,
25
+ mutation,
26
+ reason
27
+ });
28
+ const publishFailed = (mutation, cause) => ({
29
+ _tag: "PublishFailed",
30
+ source,
31
+ level: "error",
32
+ message: `${mutation} committed, but its live publish failed, so live subscribers do not hear it\n${Cause.pretty(cause)}`,
33
+ mutation,
34
+ cause
35
+ });
36
+ const clockSkewed = (facts) => ({
37
+ _tag: "ClockSkewed",
38
+ source,
39
+ level: "warning",
40
+ 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.`,
41
+ ...facts
42
+ });
4
43
  // src/refusal.ts
5
44
  /** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */
6
45
  const unauthenticatedAnswer = (refusal) => ({
@@ -26,6 +65,13 @@ var RemoteServerError = class extends Schema.TaggedError()("RemoteServerError",
26
65
  */
27
66
  var RemoteUnmet = class extends Schema.TaggedError()("RemoteUnmet", { message: Schema.String }) {};
28
67
  /**
68
+ * A writer's word that a row already holds the id an insert names, and its
69
+ * ledger records no insert of this operation that made it: `RemoteServer.write`
70
+ * answers it as the mutation's `Taken` refusal. It says nothing of the row,
71
+ * which may be hidden from whoever asked.
72
+ */
73
+ var RemoteTaken = class extends Schema.TaggedError()("RemoteTaken", { message: Schema.String }) {};
74
+ /**
29
75
  * A writer's word that the row a write would leave breaks one of its Entity's
30
76
  * invariants: `RemoteServer.write` answers it as the mutation's `Invalid`
31
77
  * refusal. `rule` and `path` are none and empty when saying them would tell
@@ -50,6 +96,32 @@ var MutationRefused = class extends Schema.TaggedError()("MutationRefused", {
50
96
  }) {};
51
97
  /** `source.read` of `fields`, through the source's `filter` when it has one. */
52
98
  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)));
99
+ /**
100
+ * A read as the handlers make it for `context.principal`: the asked fields the
101
+ * source declares and `authorize` allows, through `filter`, each record holding
102
+ * no other field. None when the principal may read none of the fields asked,
103
+ * so a caller can tell nothing to read from a row that is gone.
104
+ */
105
+ const readAs = (source, context) => {
106
+ const { ids, principal, viewer } = context;
107
+ const allowed = allowedFields(source, principal, context.fields);
108
+ if (allowed.length === 0) return Effect.succeed(Option.none());
109
+ return readFiltered(source, principal, allowed, (fields) => source.read({
110
+ ids,
111
+ fields,
112
+ principal,
113
+ viewer,
114
+ ...windowsOf(context.windows, allowed)
115
+ })).pipe(Effect.map((records) => Option.some(records.map((record) => {
116
+ const values = Object.create(null);
117
+ for (const field of allowed) if (Object.hasOwn(record.values, field)) values[field] = record.values[field];
118
+ return {
119
+ id: record.id,
120
+ values
121
+ };
122
+ }))));
123
+ };
124
+ const RowRequirement = Data.taggedEnum();
53
125
  const connectionChange = (connection, ref, position) => {
54
126
  const edge = {
55
127
  entity: ref.entity,
@@ -84,11 +156,63 @@ const windowsOf = (windows, fields) => {
84
156
  const kept = Object.fromEntries(fields.flatMap((field) => Object.hasOwn(windows, field) ? [[field, windows[field]]] : []));
85
157
  return Object.keys(kept).length === 0 ? {} : { windows: kept };
86
158
  };
159
+ /** How far from the server's clock a client's time is taken as a write's, unless `make` says. */
160
+ const DEFAULT_CLOCK_SKEW = Duration.seconds(60);
161
+ /**
162
+ * A write's time: the client's, when it sent one within `clockSkew` of this
163
+ * server's clock, or this server's. A time refused past a bound above zero is
164
+ * reported; at zero every client time is refused by design, so none is.
165
+ */
166
+ const writeTime = (server, mutation, sent) => Effect.flatMap(Clock.currentTimeMillis, (own) => Option.match(sent, {
167
+ onNone: () => Effect.succeed(own),
168
+ onSome: (time) => {
169
+ const bound = Duration.toMillis(server.clockSkew ?? DEFAULT_CLOCK_SKEW);
170
+ if (bound === 0) return Effect.succeed(own);
171
+ return Math.abs(time - own) <= bound ? Effect.succeed(time) : Effect.as(Diagnostics.report(clockSkewed({
172
+ mutation,
173
+ sent: time,
174
+ own,
175
+ bound
176
+ })), own);
177
+ }
178
+ }));
179
+ /**
180
+ * What a body's `Expr.viewer` and `Expr.now` read on this server: the viewer
181
+ * the request was given, and the server's clock. A body that reads the viewer
182
+ * in a run given none (not through a server) is refused, never read as a
183
+ * visitor's.
184
+ */
185
+ const exprContext = (body, viewer, now) => {
186
+ 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`);
187
+ return {
188
+ viewer: viewer ?? Option.none(),
189
+ now: Option.some(now)
190
+ };
191
+ };
192
+ /** Who asks, as the server's `viewer` says: none for a visitor, or on a server with no viewer. */
193
+ const viewerOf = (server, principal) => server.viewer === void 0 ? Option.none() : server.viewer(principal);
194
+ /**
195
+ * One row as `principal` may see it, through the server's own source for its
196
+ * Entity: the fields its `authorize` allows, filtered as the source filters.
197
+ * None for a row hidden or not there.
198
+ */
199
+ const rowAs = (server, principal) => (ref, fields) => {
200
+ const source = server.entities.get(ref.entity);
201
+ if (source === void 0) return Effect.fail(new RemoteServerError({ message: `No source serves ${ref.entity}` }));
202
+ const allowed = source.authorize?.(principal, fields) ?? fields;
203
+ return Effect.map(readFiltered(source, principal, allowed, (read) => source.read({
204
+ ids: [ref.id],
205
+ fields: read,
206
+ principal,
207
+ viewer: viewerOf(server, principal)
208
+ })), (records) => Option.map(Option.fromUndefinedOr(records[0]), (record) => record.values));
209
+ };
210
+ /** `read` with the services the request already runs with, so its caller needs none. */
211
+ const withServices = (read, services) => (...args) => Effect.provideContext(read(...args), services);
87
212
  /** A read batch may not carry more than this many distinct ids per entity. */
88
213
  const DEFAULT_MAX_IDS_PER_ENTITY = 1e3;
89
214
  /** A nested selection may not reach further than this many relation levels. */
90
215
  const DEFAULT_MAX_DEPTH = 8;
91
- /** Fails when the requirements name more distinct ids of one entity than `maxIds`. */
92
216
  /**
93
217
  * Each page of a relation read beside another is a source read of its own, and
94
218
  * the names come from the client, so how many one relation may have is bounded.
@@ -110,6 +234,7 @@ const checkPagesPerRelation = (requirements) => {
110
234
  if (nested !== void 0) return nested;
111
235
  }
112
236
  };
237
+ /** The entity the requirements name more distinct ids of than `maxIds`; `undefined` when none. */
113
238
  const checkIdsPerEntity = (requirements, maxIds) => {
114
239
  const ids = /* @__PURE__ */ new Map();
115
240
  for (const requirement of requirements) {
@@ -119,6 +244,58 @@ const checkIdsPerEntity = (requirements, maxIds) => {
119
244
  if (seen.size > maxIds) return requirement.entity;
120
245
  }
121
246
  };
247
+ /** Why a live subscription asks more than a read may; `undefined` when it does not. */
248
+ const liveRefusal = (requirements, maxIds) => {
249
+ const over = checkIdsPerEntity(requirements, maxIds);
250
+ if (over !== void 0) return new RemoteLiveRefused({ message: `Too many "${over}" ids in one live subscription (at most ${maxIds})` });
251
+ const paged = checkPagesPerRelation(requirements);
252
+ if (paged !== void 0) return new RemoteLiveRefused({ message: `Too many pages of "${paged}" in one live subscription` });
253
+ };
254
+ /**
255
+ * Admits each live list as a read of it is admitted, and refuses what a list
256
+ * read again every tick may not be: a query the server does not register, an
257
+ * input it does not decode, no `select` (a row is diffed by what it is drawn
258
+ * with) or one of another entity than the query lists, no `first`, or a
259
+ * `first` that, with the ids of its entity the subscription names, passes
260
+ * `maxIds`.
261
+ */
262
+ const admitQueries = (server, queries, requirements, maxIds) => Effect.gen(function* () {
263
+ const refused = (message) => new RemoteLiveRefused({ message });
264
+ const admitted = [];
265
+ const rows = /* @__PURE__ */ new Map();
266
+ for (const request of queries) {
267
+ const source = server.queries.get(request.query);
268
+ if (source === void 0) return yield* refused(`Unknown query "${request.query}" read live`);
269
+ const { select } = request;
270
+ if (select === void 0) return yield* refused(`Query "${request.query}" is read live with no select`);
271
+ if (select.entity !== source.entity) return yield* refused(`Query "${request.query}" lists "${source.entity}", but is read live selecting "${select.entity}"`);
272
+ const { first } = request.window;
273
+ if (first === void 0) return yield* refused(`Query "${request.query}" is read live with no first`);
274
+ const paged = checkPagesPerRelation([select]);
275
+ if (paged !== void 0) return yield* refused(`Too many pages of "${paged}" in one live subscription`);
276
+ const input = yield* Schema.decodeUnknownEffect(source.Input)(request.input).pipe(Effect.mapError(() => refused(`Invalid input of query "${request.query}" read live`)));
277
+ rows.set(select.entity, (rows.get(select.entity) ?? 0) + first);
278
+ admitted.push({
279
+ request,
280
+ select,
281
+ source,
282
+ input
283
+ });
284
+ }
285
+ const ids = /* @__PURE__ */ new Map();
286
+ for (const requirement of requirements) {
287
+ const seen = ids.get(requirement.entity) ?? /* @__PURE__ */ new Set();
288
+ seen.add(requirement.id);
289
+ ids.set(requirement.entity, seen);
290
+ }
291
+ 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)`);
292
+ return admitted;
293
+ });
294
+ /** A subscriber's viewer as a group key: who, none for a visitor, or no server viewer. */
295
+ const viewerKeyOf = (viewer) => viewer === void 0 ? "unset" : Option.match(viewer, {
296
+ onNone: () => "visitor",
297
+ onSome: (ref) => `as ${ref.entity}:${ref.id}`
298
+ });
122
299
  const liveHub = (entities, options = {}) => Effect.sync(() => {
123
300
  const keyOf = options.key ?? ((principal) => principal);
124
301
  const sources = new Map(entities.map((source) => [source.entity, source]));
@@ -149,12 +326,14 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
149
326
  return;
150
327
  }
151
328
  const given = (field) => values !== void 0 && source.shared !== void 0 && source.shared.has(field) && Object.hasOwn(values, field);
329
+ const perViewer = (source.perViewer ?? []).length > 0;
152
330
  const groups = /* @__PURE__ */ new Map();
153
331
  for (const subscriber of subscribers) {
154
332
  const selected = subscriber.selected.get(key);
155
333
  if (selected === void 0) continue;
156
334
  const fields = Option.getOrElse(which, () => [...new Set([...selected.fields].map(aliasedField))]);
157
335
  const principalKey = keyOf(subscriber.principal);
336
+ const viewerKey = perViewer ? viewerKeyOf(subscriber.viewer) : "";
158
337
  const sharing = groups.get(principalKey) ?? {
159
338
  principal: subscriber.principal,
160
339
  byWindows: /* @__PURE__ */ new Map()
@@ -162,7 +341,7 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
162
341
  groups.set(principalKey, sharing);
163
342
  const { byWindows } = sharing;
164
343
  const join = (windows, renames, wanted) => {
165
- const groupKey = `${stableStringify(windows)}\u0000${stableStringify(renames)}`;
344
+ const groupKey = `${stableStringify(windows)}\u0000${stableStringify(renames)}\u0000${viewerKey}`;
166
345
  const group = byWindows.get(groupKey) ?? {
167
346
  windows,
168
347
  renames,
@@ -203,15 +382,16 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
203
382
  const gone = /* @__PURE__ */ new Set();
204
383
  const read = (principal, { windows, renames, entries: group }) => Effect.gen(function* () {
205
384
  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({
385
+ const viewer = group[0]?.subscriber.viewer;
386
+ const records = yield* readAs(source, {
210
387
  ids: [ref.id],
211
- fields,
388
+ fields: requested,
212
389
  principal,
213
- ...windowsOf(windows, allowed)
214
- }))).find((candidate) => candidate.id === ref.id);
390
+ viewer,
391
+ windows
392
+ });
393
+ if (Option.isNone(records)) return;
394
+ const record = records.value.find((candidate) => candidate.id === ref.id);
215
395
  for (const { subscriber, fields: wanted } of group) {
216
396
  if (gone.has(subscriber)) continue;
217
397
  if (record === void 0) {
@@ -224,7 +404,7 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
224
404
  continue;
225
405
  }
226
406
  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];
407
+ for (const field of wanted) if (Object.hasOwn(record.values, field)) values[renamed(renames, field)] = record.values[field];
228
408
  const changed = Object.keys(values);
229
409
  if (changed.length === 0) continue;
230
410
  yield* emit(subscriber, {
@@ -241,11 +421,7 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
241
421
  if (failures.length > 0) return yield* Effect.fail(failures[0]);
242
422
  });
243
423
  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` });
424
+ subscribe: ({ requirements, after, principal, viewer }) => Stream.unwrap(Effect.gen(function* () {
249
425
  const selected = /* @__PURE__ */ new Map();
250
426
  for (const requirement of requirements) {
251
427
  const key = `${requirement.entity}:${requirement.id}`;
@@ -260,6 +436,7 @@ const liveHub = (entities, options = {}) => Effect.sync(() => {
260
436
  const subscriber = {
261
437
  selected,
262
438
  principal,
439
+ viewer,
263
440
  queue: yield* Queue.unbounded(),
264
441
  cursor: after
265
442
  };
@@ -511,7 +688,7 @@ function memory(config) {
511
688
  if (row === void 0 || !readable(name, row)) return [];
512
689
  return [{
513
690
  id,
514
- values: Object.fromEntries(fields.flatMap((field) => Object.hasOwn(row, field) ? [[field, valueFor(refsShown(readable, name, field, row[field]), windows?.[field])]] : []))
691
+ 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
692
  }];
516
693
  }),
517
694
  catch: (error) => new RemoteServerError({ message: error instanceof Error ? error.message : String(error) })
@@ -523,13 +700,17 @@ function memory(config) {
523
700
  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
701
  const queries = [...config.queries ?? [], ...[...config.domain.registry.queries.values()].filter((query) => !given.has(query.name)).map((query) => ({
525
702
  ...visible,
526
- ...RemoteServer.query(query, ({ input, window, principal }) => Effect.flatMap(readableFor(principal), (readable) => Effect.try({
703
+ ...RemoteServer.query(query, ({ input, window, principal, viewer }) => Effect.flatMap(Effect.all([readableFor(principal), Clock.currentTimeMillis]), ([readable, now]) => Effect.try({
527
704
  try: () => {
528
705
  const body = query.body;
706
+ const context = exprContext(body, viewer, now);
529
707
  const encoded = Schema.encodeSync(query.Input)(input);
530
708
  const entity = body.entity.name;
531
- const rows = store.rows(entity).filter((row) => readable(entity, row));
532
- const matched = evaluate(body, encoded, rows, { operators });
709
+ const rows = store.rows(entity).filter((row) => readable(entity, row)).map((row) => Held.fromRefs(body, row));
710
+ const matched = evaluate(body, encoded, rows, {
711
+ operators,
712
+ context
713
+ });
533
714
  const locate = (cursor) => {
534
715
  const row = rows.find((candidate) => String(candidate.id) === cursor);
535
716
  if (row === void 0) throw new Error(`Cursor "${cursor}" names a row that no longer exists`);
@@ -537,7 +718,10 @@ function memory(config) {
537
718
  index: evaluate({
538
719
  ...body,
539
720
  where: []
540
- }, encoded, [...matched, row], { operators }).indexOf(row),
721
+ }, encoded, [...matched, row], {
722
+ operators,
723
+ context
724
+ }).indexOf(row),
541
725
  exact: false
542
726
  };
543
727
  };
@@ -561,7 +745,8 @@ function memory(config) {
561
745
  const server = RemoteServer.make({
562
746
  entities: [...entities, ...config.entities ?? []],
563
747
  queries,
564
- mutations: config.mutations?.(store) ?? []
748
+ mutations: config.mutations?.(store) ?? [],
749
+ viewer: config.viewer
565
750
  });
566
751
  return {
567
752
  ...store,
@@ -569,6 +754,65 @@ function memory(config) {
569
754
  layer: Remote.clientLayer(RemoteServer.handlers(server, config.principal))
570
755
  };
571
756
  }
757
+ /** The entries of `record` whose key is in `keys`. */
758
+ const pickKeys = (record, keys) => Object.fromEntries(Object.entries(record).filter(([key]) => keys.has(key)));
759
+ /**
760
+ * A fresh read, after a mutation, of what the client shows of each row its
761
+ * outcome names: of each, the shown fields the answer left out, and every
762
+ * shown relation, since the answer's ref alone does not reach what the client
763
+ * reads of its target. Read as any read is, so `authorize` and `filter` hold.
764
+ * Only rows the read returned are answered: a row hidden from the asker keeps
765
+ * what the answer gave it rather than reading as gone.
766
+ */
767
+ const answerRead = (server, principal, options, shown, outcome) => Effect.gen(function* () {
768
+ const slices = /* @__PURE__ */ new Map();
769
+ for (const slice of shown) {
770
+ const current = slices.get(slice.entity);
771
+ slices.set(slice.entity, current === void 0 ? slice : Requirement.mergeRelation(current, slice));
772
+ }
773
+ const named = /* @__PURE__ */ new Map();
774
+ const name = (entity, id, answered) => {
775
+ const key = `${entity}:${id}`;
776
+ const row = named.get(key) ?? {
777
+ entity,
778
+ id,
779
+ answered: /* @__PURE__ */ new Set()
780
+ };
781
+ for (const field of answered) row.answered.add(field);
782
+ named.set(key, row);
783
+ };
784
+ for (const patch of outcome.entities) name(patch.entity, patch.id, Object.keys(patch.values));
785
+ for (const change of outcome.connections) if (change._tag === "Insert") name(change.edge.entity, change.edge.id, []);
786
+ for (const row of outcome.pointed ?? []) name(row.entity, row.id, []);
787
+ for (const gone of outcome.deleted) named.delete(`${gone.entity}:${gone.id}`);
788
+ const requests = [];
789
+ for (const row of named.values()) {
790
+ const slice = slices.get(row.entity);
791
+ if (slice === void 0) continue;
792
+ const relations = slice.relations ?? {};
793
+ const fields = slice.fields.filter((field) => !row.answered.has(field) || Object.hasOwn(relations, field));
794
+ const kept = new Set(fields);
795
+ requests.push({
796
+ entity: row.entity,
797
+ id: row.id,
798
+ fields,
799
+ ...slice.windows === void 0 ? {} : { windows: pickKeys(slice.windows, kept) },
800
+ ...slice.relations === void 0 ? {} : { relations: pickKeys(slice.relations, kept) }
801
+ });
802
+ }
803
+ const read = yield* RemoteServer.readHelper(server, principal, options, requests);
804
+ const reached = new Set(read.entities.map((row) => `${row.entity}:${row.id}`));
805
+ const found = requests.filter((request) => reached.has(`${request.entity}:${request.id}`));
806
+ const unreached = new Set(requests.map((request) => `${request.entity}:${request.id}`).filter((key) => !reached.has(key)));
807
+ const result = {
808
+ entities: read.entities,
809
+ settled: read.settled.filter((row) => !unreached.has(`${row.entity}:${row.id}`))
810
+ };
811
+ return found.length === 0 ? Option.none() : Option.some({
812
+ requests: found,
813
+ result
814
+ });
815
+ });
572
816
  /**
573
817
  * A Source's refusal as the client receives it: encoded by the mutation's own
574
818
  * `Refusal`. A refusal made for another mutation, or one the mutation does not
@@ -621,7 +865,8 @@ const RemoteServer = {
621
865
  input: context.input,
622
866
  principal: context.principal,
623
867
  requestId: context.requestId,
624
- operation: context.operation
868
+ operation: context.operation,
869
+ now: context.now
625
870
  }).pipe(Effect.map((outcome) => ({
626
871
  output: outcome.output,
627
872
  entities: outcome.entities ?? [],
@@ -647,6 +892,12 @@ const RemoteServer = {
647
892
  */
648
893
  unmet: (message = "The row does not hold what the write asks of it") => new RemoteUnmet({ message }),
649
894
  /**
895
+ * A writer's refusal of an insert whose id a row already holds: fail
896
+ * `insert` with it (`yield* RemoteServer.taken()`), and `RemoteServer.write`
897
+ * answers the mutation's `Taken` refusal, naming the Entity and the id.
898
+ */
899
+ taken: (message = "The id is already taken") => new RemoteTaken({ message }),
900
+ /**
650
901
  * A writer's refusal of a row that would break an invariant: fail `update`
651
902
  * or `insert` with it, naming the invariant's id and path when the caller
652
903
  * may be told them, and `RemoteServer.write` answers the mutation's
@@ -683,8 +934,9 @@ const RemoteServer = {
683
934
  * input bound to the write lands through `writer`, and the row as written
684
935
  * answers as a patch (a deletion as `deleted`). An update writes only the
685
936
  * 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
937
+ * there; an insert of an id already taken is refused as taken, alike
938
+ * whatever the row holds, unless the writer's ledger records this operation
939
+ * as the insert that made it (a retry), answered with that row; a delete of
688
940
  * a row already gone succeeds. A row that moved past the revision the write
689
941
  * `expect`s is refused as a conflict, and one that does not hold its `when`
690
942
  * as unmet; a write with a `when` needs a writer that checks it
@@ -707,13 +959,47 @@ const RemoteServer = {
707
959
  if (refused.length > 0) throw new Error(`[foldkit-remote-server] write "${mutation.name}" cannot land through its writer for ${writer.entity}: ${refused.join("; ")}`);
708
960
  const judged = Entity.invariants(write.input.entity).filter((held) => write._tag === "Update" || !Entity.readsBefore(held));
709
961
  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)`);
962
+ const contextual = write.context.flatMap(({ member }) => member._tag === "Field" ? [member.key] : []);
710
963
  if (write._tag === "Insert") {
711
- const sets = /* @__PURE__ */ new Set(["id", ...write.sets.map((set) => set.field.key)]);
964
+ const sets = /* @__PURE__ */ new Set([
965
+ "id",
966
+ ...write.sets.map((set) => set.field.key),
967
+ ...contextual
968
+ ]);
712
969
  const unset = judged.flatMap((held) => held.after.filter((key) => !sets.has(key)).map((key) => `${held.id} reads ${key}`));
713
970
  if (unset.length > 0) throw new Error(`[foldkit-remote-server] insert "${mutation.name}" leaves unset a field an invariant reads (${unset.join("; ")})`);
714
971
  }
715
972
  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
973
  const encodeInput = Schema.encodeUnknownEffect(write.input.schema);
974
+ const relations = write.input.entity.relations;
975
+ const pointers = Object.values(relations).flatMap((relation) => {
976
+ if (relation._tag !== "Relation" || relation.cardinality !== "one") return [];
977
+ const isThis = (read) => read.owner.token === relation.owner.token && read.key === relation.key;
978
+ return Object.values(relation.target().derived).some((member) => member._tag === "Derived" && Derivation.$match(member.derives, {
979
+ Supplied: () => true,
980
+ Count: ({ relation: read }) => isThis(read),
981
+ Exists: ({ relation: read }) => isThis(read)
982
+ })) ? [relation.key] : [];
983
+ });
984
+ const seenLinks = (id, principal) => writer.read !== void 0 ? writer.read({
985
+ id,
986
+ fields: pointers,
987
+ principal
988
+ }) : writer.linked !== void 0 ? writer.linked({
989
+ id,
990
+ relations: pointers
991
+ }) : Effect.succeed(Option.none());
992
+ const pointedAt = (id, principal) => pointers.length === 0 ? Effect.succeed([]) : Effect.map(seenLinks(id, principal), (held) => Option.match(held, {
993
+ onNone: () => [],
994
+ onSome: (links) => pointers.flatMap((key) => {
995
+ const ref = Object.hasOwn(links, key) ? links[key] : void 0;
996
+ return typeof ref === "string" ? [refParts(ref)] : [];
997
+ })
998
+ }));
999
+ const naming = (outcome, pointed) => pointed.length === 0 ? outcome : {
1000
+ ...outcome,
1001
+ pointed
1002
+ };
717
1003
  return {
718
1004
  mutation: mutation.name,
719
1005
  writes: {
@@ -724,7 +1010,15 @@ const RemoteServer = {
724
1010
  Input: mutation.Input,
725
1011
  Output: mutation.Output,
726
1012
  Refusal: mutation.Refusal,
727
- run: ({ input, principal, keys, operation }) => {
1013
+ run: ({ input, principal, viewer, keys, operation, now, read }) => {
1014
+ /** A path from the viewer, read through the server's sources: a row hidden or gone is null. */
1015
+ const context = Write.contextValues(write, {
1016
+ viewer,
1017
+ now: Option.some(now)
1018
+ }, (row, key) => Effect.map(read(row, [key]), (found) => Held.of(Option.match(found, {
1019
+ onNone: () => null,
1020
+ onSome: (values) => Object.hasOwn(values, key) ? values[key] : void 0
1021
+ }))));
728
1022
  const given = input;
729
1023
  const expect = Write.expected(write, given);
730
1024
  const conflict = (bound) => RemoteServer.refuse(mutation, { _tag: "Conflict" }, `${bound.entity} ${bound.id} changed since it was read`);
@@ -738,6 +1032,7 @@ const RemoteServer = {
738
1032
  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
1033
  const invalid = (writing) => Effect.catchTag(writing, "RemoteInvalid", (refused) => Effect.fail(RemoteServer.refuse(mutation, {
740
1034
  _tag: "Invalid",
1035
+ entity: Option.some(write.input.entity.name),
741
1036
  rule: refused.rule,
742
1037
  message: refused.message,
743
1038
  path: refused.path
@@ -771,13 +1066,33 @@ const RemoteServer = {
771
1066
  })
772
1067
  }));
773
1068
  };
1069
+ const request = encodeInput(given).pipe(Effect.map((encoded) => JSON.stringify([
1070
+ mutation.name,
1071
+ keys ?? null,
1072
+ encoded
1073
+ ])), Effect.mapError(() => new RemoteServerError({ message: `${mutation.name}'s input did not encode` })));
774
1074
  return Match.value(write).pipe(Match.tagsExhaustive({
775
1075
  Update: () => Effect.gen(function* () {
776
- const bound = Write.bind(write, given, keys);
1076
+ const named = Write.bind(write, given, keys);
1077
+ const set = yield* context;
1078
+ if (set.unfilled.length > 0) return yield* Effect.fail(RemoteServer.forbid());
1079
+ const bound = {
1080
+ ...named,
1081
+ values: {
1082
+ ...named.values,
1083
+ ...set.values
1084
+ },
1085
+ links: {
1086
+ ...named.links,
1087
+ ...set.links
1088
+ }
1089
+ };
1090
+ const before = yield* pointedAt(bound.id, principal);
777
1091
  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
1092
  const written = yield* invalid(unmet(bound, writer.update({
779
1093
  id: bound.id,
780
1094
  operation,
1095
+ request: yield* request,
781
1096
  values: bound.values,
782
1097
  increments: bound.increments,
783
1098
  assignments: bound.assignments,
@@ -786,28 +1101,44 @@ const RemoteServer = {
786
1101
  when: yield* when,
787
1102
  principal
788
1103
  })));
789
- if (Option.isSome(written)) return yield* answered(bound, written.value);
1104
+ if (Option.isSome(written)) return naming(yield* answered(bound, written.value), [...before, ...yield* pointedAt(bound.id, principal)]);
790
1105
  return yield* Option.isSome(expect) ? Effect.fail(conflict(bound)) : Effect.fail(new RemoteServerError({ message: `No ${bound.entity} ${bound.id} to update` }));
791
1106
  }),
792
1107
  Insert: () => Effect.gen(function* () {
793
1108
  const bound = Write.bind(write, given);
1109
+ const set = yield* context;
1110
+ if (set.unfilled.length > 0) return yield* Effect.fail(RemoteServer.forbid());
794
1111
  const row = yield* invalid(writer.insert({
795
1112
  id: bound.id,
796
- values: bound.values,
797
- links: bound.links,
1113
+ values: {
1114
+ ...bound.values,
1115
+ ...set.values
1116
+ },
1117
+ links: {
1118
+ ...bound.links,
1119
+ ...set.links
1120
+ },
1121
+ operation,
1122
+ request: yield* request,
798
1123
  principal
799
- }));
800
- return yield* answered(bound, row);
1124
+ }).pipe(Effect.catchTag("RemoteTaken", () => Effect.fail(RemoteServer.refuse(mutation, {
1125
+ _tag: "Taken",
1126
+ entity: bound.entity,
1127
+ id: bound.id
1128
+ }, `${bound.entity} ${bound.id} is already taken`)))));
1129
+ return naming(yield* answered(bound, row), yield* pointedAt(bound.id, principal));
801
1130
  }),
802
1131
  Delete: () => Effect.gen(function* () {
803
1132
  const bound = Write.bind(write, given);
804
- if ((yield* invalid(unmet(bound, writer.delete({
1133
+ const before = yield* pointedAt(bound.id, principal);
1134
+ const outcome = yield* invalid(unmet(bound, writer.delete({
805
1135
  id: bound.id,
806
1136
  expect,
807
1137
  when: yield* when,
808
1138
  principal
809
- })))) === "moved") return yield* Effect.fail(conflict(bound));
810
- return {
1139
+ })));
1140
+ if (outcome === "moved") return yield* Effect.fail(conflict(bound));
1141
+ const gone = {
811
1142
  output: {},
812
1143
  entities: [],
813
1144
  connections: [],
@@ -816,6 +1147,7 @@ const RemoteServer = {
816
1147
  id: bound.id
817
1148
  }]
818
1149
  };
1150
+ return outcome === "deleted" ? naming(gone, before) : gone;
819
1151
  })
820
1152
  }));
821
1153
  }
@@ -823,14 +1155,30 @@ const RemoteServer = {
823
1155
  },
824
1156
  query: (query, run) => ({
825
1157
  query: query.name,
1158
+ entity: query.Result.entity,
826
1159
  Input: query.Input,
827
1160
  run: (context) => run({
828
1161
  input: context.input,
829
1162
  window: context.window,
830
1163
  principal: context.principal,
1164
+ viewer: context.viewer,
831
1165
  ...context.select === void 0 ? {} : { select: context.select }
832
1166
  })
833
1167
  }),
1168
+ /**
1169
+ * Reads through `source` as the read handlers and the live hub do: only the
1170
+ * asked fields the source declares and its `authorize` allows, each record
1171
+ * through its `filter` and holding no other field. None when the principal
1172
+ * may read none of the fields asked. What a live source of its own reads
1173
+ * with, so it sends no more than a read would.
1174
+ */
1175
+ readAs,
1176
+ /**
1177
+ * The fields of `fields` that `readAs` reads for `principal`: those the
1178
+ * source declares and its `authorize` allows, in the order asked. Asks
1179
+ * nothing of the store.
1180
+ */
1181
+ allowedFields,
834
1182
  /** Streams live entity patches for a client's live requirements. */
835
1183
  live: (entity, options) => ({
836
1184
  entity: entity.name,
@@ -845,12 +1193,39 @@ const RemoteServer = {
845
1193
  * own principal.
846
1194
  */
847
1195
  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
- }),
1196
+ /**
1197
+ * The server: its sources by name. `viewer` says who asks, as a row
1198
+ * (`principal => Option.some(Remote.ref(User, principal.id))`), or none for
1199
+ * a visitor: what a declared write's `Expr.viewer` sets. A server
1200
+ * registering such an insert without one is refused here.
1201
+ *
1202
+ * `clockSkew` is how far from this server's clock a client's time (the
1203
+ * `now` a write is sent with, when the reader acted) may be and still be
1204
+ * the write's time: 60 seconds unless given, and `0` to never take it. A
1205
+ * time beyond it is replaced by the server's own, and reported as
1206
+ * `ClockSkewed`. It bounds how far a client can backdate or postdate a row.
1207
+ */
1208
+ make: (config) => {
1209
+ const served = new Set(config.entities.map((source) => source.entity));
1210
+ for (const source of config.mutations ?? []) {
1211
+ const unserved = (source.writes === void 0 ? [] : Write.contextReads(source.writes.write)).filter((entity) => !served.has(entity));
1212
+ 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`);
1213
+ }
1214
+ if (config.viewer === void 0) {
1215
+ const viewing = (config.mutations ?? []).find((source) => (source.writes?.write.context ?? []).some(({ value }) => value._tag === "Viewer"));
1216
+ 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`);
1217
+ const reading = config.entities.find((source) => (source.perViewer ?? []).length > 0);
1218
+ 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`);
1219
+ }
1220
+ return {
1221
+ entities: new Map(config.entities.map((source) => [source.entity, source])),
1222
+ mutations: new Map((config.mutations ?? []).map((source) => [source.mutation, source])),
1223
+ queries: new Map((config.queries ?? []).map((source) => [source.query, source])),
1224
+ live: new Map((config.live ?? []).map((source) => [source.entity, source])),
1225
+ viewer: config.viewer,
1226
+ ...config.clockSkew === void 0 ? {} : { clockSkew: Duration.fromInputUnsafe(config.clockSkew) }
1227
+ };
1228
+ },
854
1229
  /**
855
1230
  * Checks every source name against the declared domain, so an undeclared
856
1231
  * entity/query/mutation fails at startup rather than returning nothing at
@@ -886,6 +1261,7 @@ const RemoteServer = {
886
1261
  };
887
1262
  const fetched = /* @__PURE__ */ new Map();
888
1263
  const fetchedValues = /* @__PURE__ */ new Map();
1264
+ const viewer = viewerOf(server, principal);
889
1265
  const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
890
1266
  const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY);
891
1267
  const over = checkIdsPerEntity(requests, maxIds);
@@ -929,6 +1305,7 @@ const RemoteServer = {
929
1305
  ids: chunk,
930
1306
  fields,
931
1307
  principal,
1308
+ viewer,
932
1309
  ...windows
933
1310
  })), (chunks) => chunks.flat())).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteReadError({ message: error.message }))));
934
1311
  for (const record of records) {
@@ -977,8 +1354,10 @@ const RemoteServer = {
977
1354
  * The request and its payload are decoded by the protocol's own schemas
978
1355
  * before a handler sees them, so an operation name is one of Remote's three
979
1356
  * 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.
1357
+ * could not be told a 401; a refusal of who is asking a 403; a mutation's
1358
+ * declared refusal a 422, or a 409 when it is `Refusal.taken`; a handler's
1359
+ * failure a 500 with its message; a defect a 500 that says nothing of it,
1360
+ * its cause reported as a `ServerDefect` (`Diagnostics`, by default the log).
982
1361
  * `Remote.json` and `Remote.http` are the other end.
983
1362
  */
984
1363
  answer: (handlers, body) => {
@@ -1003,7 +1382,7 @@ const RemoteServer = {
1003
1382
  status: 500,
1004
1383
  body: { error: error.message }
1005
1384
  } : {
1006
- status: 422,
1385
+ status: Refusal.isTaken(error.refusal) ? 409 : 422,
1007
1386
  body: {
1008
1387
  error: error.message,
1009
1388
  refusal: error.refusal
@@ -1011,10 +1390,10 @@ const RemoteServer = {
1011
1390
  })), Effect.catch((error) => Effect.succeed({
1012
1391
  status: 500,
1013
1392
  body: { error: error.message }
1014
- })), Effect.catchCause(() => Effect.succeed({
1393
+ })), Effect.catchCause((cause) => Diagnostics.report(serverDefect(cause)).pipe(Effect.as({
1015
1394
  status: 500,
1016
1395
  body: { error: "Internal error" }
1017
- })));
1396
+ }))));
1018
1397
  },
1019
1398
  /**
1020
1399
  * Compiles the server into Remote's RPC handlers, answering as `principal`:
@@ -1040,18 +1419,22 @@ const RemoteServer = {
1040
1419
  const outcome = yield* source.run({
1041
1420
  input,
1042
1421
  principal: caller,
1422
+ viewer: server.viewer === void 0 ? Option.none() : server.viewer(caller),
1043
1423
  requestId: payload.requestId,
1044
1424
  operation: Option.fromUndefinedOr(payload.operation),
1425
+ now: yield* writeTime(server, payload.mutation, Option.fromUndefinedOr(payload.now)),
1426
+ read: withServices(rowAs(server, caller), yield* Effect.context()),
1045
1427
  keys: payload.keys
1046
1428
  }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteMutationError({ message: error.message }))), Effect.catchTag("MutationRefused", (refused) => refusalError(source.Refusal, payload.mutation, refused)));
1047
1429
  const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation output" }))));
1430
+ 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()))));
1048
1431
  const hub = options.live;
1049
1432
  if (hub !== void 0) {
1050
1433
  const stored = source.writes !== void 0;
1051
1434
  yield* Effect.forEach(outcome.entities, (patch) => hub.changed({
1052
1435
  entity: patch.entity,
1053
1436
  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)));
1437
+ }, 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
1438
  }
1056
1439
  return {
1057
1440
  output,
@@ -1064,7 +1447,11 @@ const RemoteServer = {
1064
1447
  deleted: outcome.deleted.map((gone) => ({
1065
1448
  entity: gone.entity,
1066
1449
  id: gone.id
1067
- }))
1450
+ })),
1451
+ ...Option.match(read, {
1452
+ onNone: () => ({}),
1453
+ onSome: (value) => ({ read: value })
1454
+ })
1068
1455
  };
1069
1456
  }),
1070
1457
  FoldkitRemoteQuery: Effect.fn("RemoteServer.FoldkitRemoteQuery")(function* (payload) {
@@ -1081,6 +1468,7 @@ const RemoteServer = {
1081
1468
  input,
1082
1469
  window: payload.window,
1083
1470
  principal: caller,
1471
+ viewer: viewerOf(server, caller),
1084
1472
  ...select === void 0 ? {} : { select }
1085
1473
  }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
1086
1474
  if (select === void 0) return {
@@ -1113,28 +1501,50 @@ const RemoteServer = {
1113
1501
  FoldkitRemoteLive: (payload) => {
1114
1502
  const mismatch = protocolMismatch(payload.version);
1115
1503
  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) => {
1504
+ const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY);
1505
+ const refusal = liveRefusal(payload.requirements, maxIds);
1506
+ if (refusal !== void 0) return Stream.fail(refusal);
1507
+ return Stream.unwrap(Effect.gen(function* () {
1508
+ const admitted = yield* admitQueries(server, payload.queries ?? [], payload.requirements, maxIds);
1509
+ const caller = yield* asking;
1510
+ const viewer = viewerOf(server, caller);
1511
+ const queries = admitted.map(({ request, select, source, input }) => ({
1512
+ identity: queryIdentity(request.query, request.input),
1513
+ select,
1514
+ edges: Effect.map(source.run({
1515
+ input,
1516
+ window: request.window,
1517
+ principal: caller,
1518
+ viewer,
1519
+ select
1520
+ }), (page) => page.edges)
1521
+ }));
1522
+ const streams = [.../* @__PURE__ */ new Set([...payload.requirements.map((request) => request.entity), ...queries.map((query) => query.select.entity)])].flatMap((entity) => {
1118
1523
  const source = server.live.get(entity);
1119
1524
  if (source === void 0) return [];
1120
1525
  return [source.subscribe({
1121
1526
  requirements: payload.requirements.filter((request) => request.entity === entity),
1527
+ queries: queries.filter((query) => query.select.entity === entity),
1122
1528
  after: payload.after,
1123
- principal: caller
1529
+ principal: caller,
1530
+ viewer
1124
1531
  })];
1125
1532
  });
1126
1533
  if (options.live !== void 0) streams.push(options.live.subscribe({
1127
1534
  requirements: payload.requirements,
1128
1535
  after: payload.after,
1129
1536
  principal: caller,
1130
- maxIdsPerEntity: options.maxIdsPerEntity
1537
+ viewer
1131
1538
  }));
1132
- return Stream.mergeAll(streams, { concurrency: "unbounded" }).pipe(Stream.mapError((error) => new RemoteLiveError({ message: error.message })));
1539
+ return Stream.mergeAll(streams, { concurrency: "unbounded" }).pipe(Stream.mapAccum(() => payload.after, (cursor, change) => [cursor + 1, [{
1540
+ ...change,
1541
+ cursor: cursor + 1
1542
+ }]]), Stream.mapError((error) => new RemoteLiveError({ message: error.message })));
1133
1543
  }));
1134
1544
  }
1135
1545
  };
1136
1546
  }
1137
1547
  };
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 };
1548
+ export { RemoteTaken as a, exprContext as c, evaluate$1 as d, supported as f, RemoteServerError as i, QueryEvaluateError as l, serverDefect as m, RemoteInvalid as n, RemoteUnmet as o, unauthenticatedAnswer as p, RemoteServer as r, RowRequirement as s, MutationRefused as t, assertSupported$1 as u };
1139
1549
 
1140
- //# sourceMappingURL=src-yDMwdGiL.mjs.map
1550
+ //# sourceMappingURL=src-ZV9pARkU.mjs.map