foldkit-remote-server 0.13.4 → 0.15.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.
@@ -0,0 +1,1060 @@
1
+ import { Context, Effect, Match, Option, Queue, Schema, Stream } from "effect";
2
+ import { QueryEvaluateError, Write, assertSupported, 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";
4
+ //#region src/refusal.ts
5
+ /** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */
6
+ const unauthenticatedAnswer = (refusal) => ({
7
+ status: 401,
8
+ body: {
9
+ error: refusal.message,
10
+ unauthenticated: refusal.reason === void 0 ? {} : { reason: refusal.reason }
11
+ }
12
+ });
13
+ //#endregion
14
+ //#region src/index.ts
15
+ /**
16
+ * `foldkit-remote-server` — server-side Sources and handler compilation.
17
+ *
18
+ * Owns entity/query Sources, **selection authorization**, normalization, and
19
+ * turning them into Effect RPC handlers. It does not own HTTP, serialization, or
20
+ * auth protocol; `principal` is resolved outside, and passed in or provided.
21
+ */
22
+ var RemoteServerError = class extends Schema.TaggedError()("RemoteServerError", { message: Schema.String }) {};
23
+ /**
24
+ * A mutation Source's refusal, as the value its descriptor's `Refusal`
25
+ * declares: made with `RemoteServer.refuse`, which checks the value's type
26
+ * against the mutation, and sent to the client encoded, beside a message.
27
+ */
28
+ var MutationRefused = class extends Schema.TaggedError()("MutationRefused", {
29
+ /** The mutation the refusal was made for: a Source refusing as another is a bug. */
30
+ mutation: Schema.String,
31
+ refusal: Schema.Unknown,
32
+ /** What a person reads: the error's message beside the refusal. */
33
+ message: Schema.String
34
+ }) {};
35
+ /** `source.read` of `fields`, through the source's `filter` when it has one. */
36
+ 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)));
37
+ const connectionChange = (connection, ref, position) => {
38
+ const edge = {
39
+ entity: ref.entity,
40
+ id: ref.id,
41
+ key: entityKey(ref.entity, ref.id)
42
+ };
43
+ return position === "remove" ? {
44
+ _tag: "Remove",
45
+ connection: connectionIdentity(connection),
46
+ edge
47
+ } : {
48
+ _tag: "Insert",
49
+ connection: connectionIdentity(connection),
50
+ position,
51
+ edge
52
+ };
53
+ };
54
+ /**
55
+ * The requested fields, in request order, that the source declares and the
56
+ * principal may read. Never a field the client did not request, even if a
57
+ * permissive `authorize` returns more.
58
+ */
59
+ const allowedFields = (source, principal, requested) => {
60
+ const declared = source.fields === void 0 ? requested : requested.filter((field) => source.fields.has(field));
61
+ if (declared.length === 0) return [];
62
+ const permitted = new Set(source.authorize === void 0 ? declared : source.authorize(principal, declared));
63
+ return declared.filter((field) => permitted.has(field));
64
+ };
65
+ /** The windows of the fields being read; only a field being read carries its window. */
66
+ const windowsOf = (windows, fields) => {
67
+ if (windows === void 0) return {};
68
+ const kept = Object.fromEntries(fields.flatMap((field) => Object.hasOwn(windows, field) ? [[field, windows[field]]] : []));
69
+ return Object.keys(kept).length === 0 ? {} : { windows: kept };
70
+ };
71
+ /** A read batch may not carry more than this many distinct ids per entity. */
72
+ const DEFAULT_MAX_IDS_PER_ENTITY = 1e3;
73
+ /** A nested selection may not reach further than this many relation levels. */
74
+ const DEFAULT_MAX_DEPTH = 8;
75
+ /** Fails when the requirements name more distinct ids of one entity than `maxIds`. */
76
+ /**
77
+ * Each page of a relation read beside another is a source read of its own, and
78
+ * the names come from the client, so how many one relation may have is bounded.
79
+ * A screen shows a list and a page or two of it, not dozens.
80
+ */
81
+ const MAX_PAGES_PER_RELATION = 4;
82
+ /** The relation a request pages more ways than allowed, at any depth; `undefined` when none. */
83
+ const checkPagesPerRelation = (requirements) => {
84
+ for (const requirement of requirements) {
85
+ const pages = /* @__PURE__ */ new Map();
86
+ for (const name of requirement.fields) {
87
+ if (!name.includes(RELATION_ALIAS)) continue;
88
+ const field = aliasedField(name);
89
+ const count = (pages.get(field) ?? 0) + 1;
90
+ if (count > MAX_PAGES_PER_RELATION) return `${requirement.entity}.${field}`;
91
+ pages.set(field, count);
92
+ }
93
+ const nested = checkPagesPerRelation(Object.values(requirement.relations ?? {}));
94
+ if (nested !== void 0) return nested;
95
+ }
96
+ };
97
+ const checkIdsPerEntity = (requirements, maxIds) => {
98
+ const ids = /* @__PURE__ */ new Map();
99
+ for (const requirement of requirements) {
100
+ const seen = ids.get(requirement.entity) ?? /* @__PURE__ */ new Set();
101
+ seen.add(requirement.id);
102
+ ids.set(requirement.entity, seen);
103
+ if (seen.size > maxIds) return requirement.entity;
104
+ }
105
+ };
106
+ const liveHub = (entities, options = {}) => Effect.sync(() => {
107
+ const keyOf = options.key ?? ((principal) => principal);
108
+ const sources = new Map(entities.map((source) => [source.entity, source]));
109
+ const subscribers = /* @__PURE__ */ new Set();
110
+ const emit = (subscriber, change) => {
111
+ subscriber.cursor += 1;
112
+ return Queue.offer(subscriber.queue, {
113
+ ...change,
114
+ cursor: subscriber.cursor
115
+ });
116
+ };
117
+ /**
118
+ * Re-reads row `ref` for each subscriber that selects it, of `which` of
119
+ * its fields (none: every field it selects), and sends what it now sees:
120
+ * a patch, or, where the row is no longer there to it, a deletion. One
121
+ * group's failed read fails the call after the others are sent.
122
+ */
123
+ const refresh = (ref, which, values) => Effect.gen(function* () {
124
+ const key = `${ref.entity}:${ref.id}`;
125
+ const source = sources.get(ref.entity);
126
+ if (source === void 0) {
127
+ if (Option.isSome(which)) return;
128
+ for (const subscriber of subscribers) if (subscriber.selected.has(key)) yield* emit(subscriber, {
129
+ _tag: "EntityDeleted",
130
+ entity: ref.entity,
131
+ id: ref.id
132
+ });
133
+ return;
134
+ }
135
+ const given = (field) => values !== void 0 && source.shared !== void 0 && source.shared.has(field) && Object.hasOwn(values, field);
136
+ const groups = /* @__PURE__ */ new Map();
137
+ for (const subscriber of subscribers) {
138
+ const selected = subscriber.selected.get(key);
139
+ if (selected === void 0) continue;
140
+ const fields = Option.getOrElse(which, () => [...new Set([...selected.fields].map(aliasedField))]);
141
+ const principalKey = keyOf(subscriber.principal);
142
+ const sharing = groups.get(principalKey) ?? {
143
+ principal: subscriber.principal,
144
+ byWindows: /* @__PURE__ */ new Map()
145
+ };
146
+ groups.set(principalKey, sharing);
147
+ const { byWindows } = sharing;
148
+ const join = (windows, renames, wanted) => {
149
+ const groupKey = `${stableStringify(windows)}\u0000${stableStringify(renames)}`;
150
+ const group = byWindows.get(groupKey) ?? {
151
+ windows,
152
+ renames,
153
+ entries: []
154
+ };
155
+ byWindows.set(groupKey, group);
156
+ group.entries.push({
157
+ subscriber,
158
+ fields: wanted
159
+ });
160
+ };
161
+ const selects = fields.filter((field) => selected.fields.has(field));
162
+ const sent = selects.filter((field) => given(field) && !selected.windows.has(field));
163
+ if (sent.length > 0) {
164
+ const patch = Object.create(null);
165
+ for (const field of sent) patch[field] = values[field];
166
+ yield* emit(subscriber, {
167
+ _tag: "EntityPatched",
168
+ entity: ref.entity,
169
+ id: ref.id,
170
+ values: patch,
171
+ changed: sent
172
+ });
173
+ }
174
+ const sentSet = new Set(sent);
175
+ const wanted = selects.filter((field) => !sentSet.has(field));
176
+ if (wanted.length > 0) join(Object.fromEntries(wanted.flatMap((field) => {
177
+ const window = selected.windows.get(field);
178
+ return window === void 0 ? [] : [[field, window]];
179
+ })), {}, wanted);
180
+ for (const alias of selected.fields) {
181
+ const window = selected.windows.get(alias);
182
+ const field = aliasedField(alias);
183
+ if (field === alias || window === void 0 || !fields.includes(field)) continue;
184
+ join({ [field]: window }, { [field]: alias }, [field]);
185
+ }
186
+ }
187
+ const gone = /* @__PURE__ */ new Set();
188
+ const read = (principal, { windows, renames, entries: group }) => Effect.gen(function* () {
189
+ const requested = [...new Set(group.flatMap((entry) => entry.fields))];
190
+ const allowed = allowedFields(source, principal, requested);
191
+ if (allowed.length === 0) return;
192
+ const allowedSet = new Set(allowed);
193
+ const record = (yield* readFiltered(source, principal, allowed, (fields) => source.read({
194
+ ids: [ref.id],
195
+ fields,
196
+ principal,
197
+ ...windowsOf(windows, allowed)
198
+ }))).find((candidate) => candidate.id === ref.id);
199
+ for (const { subscriber, fields: wanted } of group) {
200
+ if (gone.has(subscriber)) continue;
201
+ if (record === void 0) {
202
+ gone.add(subscriber);
203
+ yield* emit(subscriber, {
204
+ _tag: "EntityDeleted",
205
+ entity: ref.entity,
206
+ id: ref.id
207
+ });
208
+ continue;
209
+ }
210
+ const values = Object.create(null);
211
+ for (const field of wanted) if (allowedSet.has(field) && Object.hasOwn(record.values, field)) values[renamed(renames, field)] = record.values[field];
212
+ const changed = Object.keys(values);
213
+ if (changed.length === 0) continue;
214
+ yield* emit(subscriber, {
215
+ _tag: "EntityPatched",
216
+ entity: ref.entity,
217
+ id: ref.id,
218
+ values,
219
+ changed
220
+ });
221
+ }
222
+ });
223
+ const failures = [];
224
+ for (const { principal, byWindows } of groups.values()) for (const group of byWindows.values()) yield* read(principal, group).pipe(Effect.catch((error) => Effect.sync(() => void failures.push(error))));
225
+ if (failures.length > 0) return yield* Effect.fail(failures[0]);
226
+ });
227
+ return {
228
+ subscribe: ({ requirements, after, principal, maxIdsPerEntity }) => Stream.unwrap(Effect.gen(function* () {
229
+ const over = checkIdsPerEntity(requirements, Math.max(1, maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY));
230
+ if (over !== void 0) return yield* new RemoteServerError({ message: `Too many "${over}" ids in one live subscription` });
231
+ const paged = checkPagesPerRelation(requirements);
232
+ if (paged !== void 0) return yield* new RemoteServerError({ message: `Too many pages of "${paged}" in one live subscription` });
233
+ const selected = /* @__PURE__ */ new Map();
234
+ for (const requirement of requirements) {
235
+ const key = `${requirement.entity}:${requirement.id}`;
236
+ const entry = selected.get(key) ?? {
237
+ fields: /* @__PURE__ */ new Set(),
238
+ windows: /* @__PURE__ */ new Map()
239
+ };
240
+ for (const field of requirement.fields) entry.fields.add(field);
241
+ for (const [field, window] of Object.entries(requirement.windows ?? {})) entry.windows.set(field, window);
242
+ selected.set(key, entry);
243
+ }
244
+ const subscriber = {
245
+ selected,
246
+ principal,
247
+ queue: yield* Queue.unbounded(),
248
+ cursor: after
249
+ };
250
+ subscribers.add(subscriber);
251
+ return Stream.fromQueue(subscriber.queue).pipe(Stream.ensuring(Effect.sync(() => void subscribers.delete(subscriber))));
252
+ })),
253
+ changed: (ref, fields, values) => refresh(ref, Option.some(fields), values),
254
+ deleted: (ref) => refresh(ref, Option.none(), void 0),
255
+ size: Effect.sync(() => subscribers.size)
256
+ };
257
+ });
258
+ const protocolMismatch = (received) => received === REMOTE_PROTOCOL_VERSION ? void 0 : new RemoteProtocolError({
259
+ message: `Remote protocol version ${received} is not ${REMOTE_PROTOCOL_VERSION}`,
260
+ expected: REMOTE_PROTOCOL_VERSION,
261
+ received
262
+ });
263
+ /**
264
+ * The name a field is answered under. A requested field is client input, so
265
+ * `constructor` must find no rename rather than `Object.prototype`'s.
266
+ */
267
+ const renamed = (renames, field) => Object.hasOwn(renames, field) ? renames[field] : field;
268
+ const pickNames = (record, names) => {
269
+ if (record === void 0) return void 0;
270
+ const picked = names.flatMap((name) => Object.hasOwn(record, name) ? [[name, record[name]]] : []);
271
+ return picked.length === 0 ? void 0 : Object.fromEntries(picked);
272
+ };
273
+ /**
274
+ * A request's aliased fields, each as a read of its own. `comments@first=10` is
275
+ * the `comments` relation read with the alias's window, so a source sees the
276
+ * field it knows and one window for it, while the whole list rides beside it in
277
+ * another read. The answer goes back under the alias, which is also the key of
278
+ * the relation followed from it.
279
+ */
280
+ const splitAliases = (request) => {
281
+ const aliases = request.fields.filter((field) => field.includes(RELATION_ALIAS));
282
+ if (aliases.length === 0) return [request];
283
+ const plain = request.fields.filter((field) => !field.includes(RELATION_ALIAS));
284
+ const keyed = (entries) => Object.assign(Object.create(null), entries);
285
+ const building = [{
286
+ fields: [...plain],
287
+ windows: keyed(pickNames(request.windows, plain)),
288
+ relations: keyed(pickNames(request.relations, plain)),
289
+ renames: keyed()
290
+ }];
291
+ for (const alias of aliases) {
292
+ const window = request.windows?.[alias];
293
+ if (window === void 0) continue;
294
+ const field = aliasedField(alias);
295
+ let part = building.find((candidate) => !candidate.fields.includes(field));
296
+ if (part === void 0) {
297
+ part = {
298
+ fields: [],
299
+ windows: keyed(),
300
+ relations: keyed(),
301
+ renames: keyed()
302
+ };
303
+ building.push(part);
304
+ }
305
+ part.fields.push(field);
306
+ part.windows[field] = window;
307
+ part.renames[field] = alias;
308
+ const relation = request.relations?.[alias];
309
+ if (relation !== void 0) part.relations[alias] = relation;
310
+ }
311
+ return building.filter((part) => part.fields.length > 0).map((part) => ({
312
+ entity: request.entity,
313
+ id: request.id,
314
+ fields: part.fields,
315
+ ...Object.keys(part.windows).length === 0 ? {} : { windows: part.windows },
316
+ ...Object.keys(part.relations).length === 0 ? {} : { relations: part.relations },
317
+ ...Object.keys(part.renames).length === 0 ? {} : { renames: part.renames }
318
+ }));
319
+ };
320
+ /**
321
+ * One level's requests grouped per entity and window signature: ids and
322
+ * slices unioned. Requests that page a relation differently are separate
323
+ * groups, so one window never answers for another id.
324
+ */
325
+ const groupByEntity = (requests) => {
326
+ const grouped = /* @__PURE__ */ new Map();
327
+ for (const request of requests.flatMap(splitAliases)) {
328
+ const renames = request.renames ?? {};
329
+ const groupKey = `${request.entity}\u0000${stableStringify(request.windows ?? null)}\u0000${stableStringify(renames)}`;
330
+ const group = grouped.get(groupKey);
331
+ if (group === void 0) grouped.set(groupKey, {
332
+ ids: /* @__PURE__ */ new Map([[request.id, new Set(request.fields)]]),
333
+ slice: Requirement.mergeRelation({
334
+ entity: request.entity,
335
+ fields: []
336
+ }, request),
337
+ renames
338
+ });
339
+ else {
340
+ const asked = group.ids.get(request.id) ?? /* @__PURE__ */ new Set();
341
+ for (const field of request.fields) asked.add(field);
342
+ group.ids.set(request.id, asked);
343
+ group.slice = Requirement.mergeRelation(group.slice, request);
344
+ }
345
+ }
346
+ return [...grouped.values()];
347
+ };
348
+ /**
349
+ * One page of ordered items for a window, as a real server pages them. A
350
+ * cursor is an item's id: a forward page starts at the `after` it was asked
351
+ * for and ends at its last item while more follow, a backward page the
352
+ * mirror, so a page fetched from another's end cursor joins it.
353
+ *
354
+ * `locate` places a cursor that is not among the items, as a keyset does: a
355
+ * row that stopped matching still has a place in the order. Without it, such
356
+ * a cursor is an error. A page of no items has no id of its own to end at, so
357
+ * with more beyond it and no cursor to repeat, its boundary is `Unknown`.
358
+ */
359
+ const pageOf = (items, window, idOf, locate) => {
360
+ if (window.after !== void 0 && window.before !== void 0 || window.first !== void 0 && window.last !== void 0) throw new Error("A query window cannot combine after with before, or first with last");
361
+ const position = (cursor) => {
362
+ const index = items.findIndex((item) => idOf(item) === cursor);
363
+ if (index >= 0) return {
364
+ index,
365
+ exact: true
366
+ };
367
+ if (locate !== void 0) return locate(cursor);
368
+ throw new Error(`Cursor "${cursor}" names nothing in these results`);
369
+ };
370
+ const cursor = (id) => ({
371
+ _tag: "Cursor",
372
+ cursor: id
373
+ });
374
+ const terminal = { _tag: "Terminal" };
375
+ const unknown = { _tag: "Unknown" };
376
+ if (window.last !== void 0 || window.before !== void 0) {
377
+ const to = window.before === void 0 ? items.length : position(window.before).index;
378
+ const from = window.last === void 0 ? 0 : Math.max(0, to - window.last);
379
+ const page = items.slice(from, to);
380
+ return {
381
+ items: page,
382
+ start: from === 0 ? terminal : page.length > 0 ? cursor(idOf(page[0])) : window.before === void 0 ? unknown : cursor(window.before),
383
+ end: window.before === void 0 ? terminal : cursor(window.before)
384
+ };
385
+ }
386
+ const at = window.after === void 0 ? void 0 : position(window.after);
387
+ const from = at === void 0 ? 0 : at.exact ? at.index + 1 : at.index;
388
+ const to = window.first === void 0 ? items.length : Math.min(items.length, from + window.first);
389
+ const page = items.slice(from, to);
390
+ const end = to >= items.length ? terminal : page.length > 0 ? cursor(idOf(page.at(-1))) : window.after === void 0 ? unknown : cursor(window.after);
391
+ return {
392
+ items: page,
393
+ start: window.after === void 0 ? terminal : cursor(window.after),
394
+ end
395
+ };
396
+ };
397
+ function memory(config) {
398
+ const declared = config.domain.registry.entities;
399
+ const extra = /* @__PURE__ */ new Set();
400
+ for (const source of config.entities ?? []) {
401
+ if (declared.has(source.entity)) throw new Error(`RemoteServer.memory: "${source.entity}" is a declared entity, which the rows serve; give its rows, or leave it out of the domain and keep its source`);
402
+ if (extra.has(source.entity)) throw new Error(`RemoteServer.memory: two sources in \`entities\` serve "${source.entity}"`);
403
+ extra.add(source.entity);
404
+ }
405
+ const authorize = config.authorize ?? {};
406
+ const filter = config.filter ?? {};
407
+ const shared = config.shared ?? {};
408
+ for (const [option, given] of [
409
+ ["authorize", authorize],
410
+ ["filter", filter],
411
+ ["shared", shared]
412
+ ]) {
413
+ const unknown = Object.keys(given).filter((name) => !config.domain.registry.entities.has(name));
414
+ if (unknown.length > 0) throw new Error(`RemoteServer.memory: \`${option}\` names ${unknown.map((name) => `"${name}"`).join(", ")}, which the domain does not declare`);
415
+ }
416
+ for (const [name, fields] of Object.entries(shared)) {
417
+ const entity = config.domain.registry.entities.get(name);
418
+ const declared = entity.members ?? entity.fields;
419
+ const unserved = fields.filter((field) => declared !== void 0 && !Object.hasOwn(declared, field));
420
+ if (unserved.length > 0) throw new Error(`RemoteServer.memory: ${name}'s shared fields name no member: ${unserved.join(", ")}`);
421
+ }
422
+ const everyRow = () => true;
423
+ const readableFor = (principal) => config.readable === void 0 ? Effect.succeed(everyRow) : config.readable(principal, (entity, id) => Option.fromUndefinedOr(table(entity).get(id)));
424
+ const tables = /* @__PURE__ */ new Map();
425
+ const table = (entity) => {
426
+ const existing = tables.get(entity);
427
+ if (existing !== void 0) return existing;
428
+ const created = /* @__PURE__ */ new Map();
429
+ tables.set(entity, created);
430
+ return created;
431
+ };
432
+ for (const [entity, rows] of Object.entries(config.rows)) for (const row of rows) table(entity).set(String(row.id), { ...row });
433
+ const store = {
434
+ rows: (entity) => [...table(entity).values()],
435
+ write: (entity, id, values) => {
436
+ table(entity).set(id, {
437
+ ...table(entity).get(id),
438
+ id,
439
+ ...values
440
+ });
441
+ },
442
+ remove: (entity, id) => {
443
+ table(entity).delete(id);
444
+ }
445
+ };
446
+ const valueFor = (value, window) => {
447
+ if (window === void 0 || !Array.isArray(value)) return value;
448
+ const refs = [...new Set(value)];
449
+ const idOf = (ref) => ref.slice(ref.indexOf(":") + 1);
450
+ const named = (cursor) => cursor === void 0 ? void 0 : cursor.includes(":") ? idOf(cursor) : cursor;
451
+ let page;
452
+ try {
453
+ page = pageOf(refs, {
454
+ ...window,
455
+ after: named(window.after),
456
+ before: named(window.before)
457
+ }, idOf);
458
+ } catch {
459
+ return {
460
+ refs: [],
461
+ hasNext: false,
462
+ hasPrevious: false
463
+ };
464
+ }
465
+ return {
466
+ refs: page.items,
467
+ hasNext: page.end._tag === "Cursor",
468
+ hasPrevious: page.start._tag === "Cursor"
469
+ };
470
+ };
471
+ const relationsOf = new Map([...config.domain.registry.entities].map(([name, descriptor]) => [name, new Set(Object.entries(descriptor.fields).flatMap(([field, schema]) => relationShape(schema) === void 0 ? [] : [field]))]));
472
+ const refsShown = (readable, entity, field, value) => {
473
+ if (readable === everyRow || relationsOf.get(entity)?.has(field) !== true) return value;
474
+ const shown = (ref) => {
475
+ if (typeof ref !== "string") return true;
476
+ const { entity: target, id } = refParts(ref);
477
+ const row = table(target).get(id);
478
+ return row !== void 0 && readable(target, row);
479
+ };
480
+ if (Array.isArray(value)) return value.filter(shown);
481
+ return shown(value) ? value : null;
482
+ };
483
+ const visible = config.readable === void 0 ? {} : { visible: config.readable };
484
+ const entities = [...config.domain.registry.entities.keys()].map((name) => ({
485
+ ...visible,
486
+ ...RemoteServer.entity({ name }, {
487
+ ...Object.hasOwn(authorize, name) ? { authorize: authorize[name] } : {},
488
+ ...Object.hasOwn(filter, name) ? { filter: filter[name] } : {},
489
+ ...Object.hasOwn(shared, name) ? { shared: shared[name] } : {},
490
+ read: ({ ids, fields, windows, principal }) => Effect.flatMap(readableFor(principal), (readable) => Effect.try({
491
+ try: () => ids.flatMap((id) => {
492
+ const row = table(name).get(id);
493
+ if (row === void 0 || !readable(name, row)) return [];
494
+ return [{
495
+ id,
496
+ values: Object.fromEntries(fields.flatMap((field) => Object.hasOwn(row, field) ? [[field, valueFor(refsShown(readable, name, field, row[field]), windows?.[field])]] : []))
497
+ }];
498
+ }),
499
+ catch: (error) => new RemoteServerError({ message: error instanceof Error ? error.message : String(error) })
500
+ }))
501
+ })
502
+ }));
503
+ const given = new Set((config.queries ?? []).map((source) => source.query));
504
+ const bodiless = [...config.domain.registry.queries.values()].filter((query) => query.body === void 0 && !given.has(query.name));
505
+ 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\`.`);
506
+ const queries = [...config.queries ?? [], ...[...config.domain.registry.queries.values()].filter((query) => !given.has(query.name)).map((query) => ({
507
+ ...visible,
508
+ ...RemoteServer.query(query, ({ input, window, principal }) => Effect.flatMap(readableFor(principal), (readable) => Effect.try({
509
+ try: () => {
510
+ const body = query.body;
511
+ const encoded = Schema.encodeSync(query.Input)(input);
512
+ const entity = body.entity.name;
513
+ const rows = store.rows(entity).filter((row) => readable(entity, row));
514
+ const matched = evaluate(body, encoded, rows);
515
+ const locate = (cursor) => {
516
+ const row = rows.find((candidate) => String(candidate.id) === cursor);
517
+ if (row === void 0) throw new Error(`Cursor "${cursor}" names a row that no longer exists`);
518
+ return {
519
+ index: evaluate({
520
+ ...body,
521
+ where: []
522
+ }, encoded, [...matched, row]).indexOf(row),
523
+ exact: false
524
+ };
525
+ };
526
+ const page = pageOf(matched, window, (row) => String(row.id), locate);
527
+ return {
528
+ edges: page.items.map((row) => {
529
+ const id = String(row.id);
530
+ return {
531
+ entity,
532
+ id,
533
+ key: entityKey(entity, id)
534
+ };
535
+ }),
536
+ start: page.start,
537
+ end: page.end
538
+ };
539
+ },
540
+ catch: (error) => new RemoteServerError({ message: error instanceof Error ? error.message : String(error) })
541
+ })))
542
+ }))];
543
+ const server = RemoteServer.make({
544
+ entities: [...entities, ...config.entities ?? []],
545
+ queries,
546
+ mutations: config.mutations?.(store) ?? []
547
+ });
548
+ return {
549
+ ...store,
550
+ server,
551
+ layer: Remote.clientLayer(RemoteServer.handlers(server, config.principal))
552
+ };
553
+ }
554
+ /**
555
+ * A Source's refusal as the client receives it: encoded by the mutation's own
556
+ * `Refusal`. A refusal made for another mutation, or one the mutation does not
557
+ * declare, is this side's bug, and says so without the value.
558
+ */
559
+ const refusalError = (Refusal, mutation, refused) => Effect.gen(function* () {
560
+ const invalid = new RemoteMutationError({ message: "Invalid mutation refusal" });
561
+ if (refused.mutation !== mutation) return yield* invalid;
562
+ const encoded = yield* Schema.encodeUnknownEffect(Refusal)(refused.refusal).pipe(Effect.mapError(() => invalid));
563
+ return yield* new RemoteMutationError({
564
+ message: refused.message,
565
+ refusal: encoded
566
+ });
567
+ });
568
+ const RemoteServer = {
569
+ /** A backend held in memory, for a first run, a test or a demo. See `memory`. */
570
+ memory,
571
+ /** A mutation outcome's report that `ref` now heads the connection. */
572
+ prepend: (connection, ref) => connectionChange(connection, ref, "prepend"),
573
+ /** A mutation outcome's report that `ref` now ends the connection. */
574
+ append: (connection, ref) => connectionChange(connection, ref, "append"),
575
+ /** A mutation outcome's report that `ref` left the connection. */
576
+ remove: (connection, ref) => connectionChange(connection, ref, "remove"),
577
+ /**
578
+ * An entity source. Given the Entity, every member it declares (fields,
579
+ * relations, derived members) may be requested; given anything with a
580
+ * `name` and `fields`, those fields. A request for anything else never
581
+ * reaches `read` or `authorize`. Given only a `name`, every field passes.
582
+ */
583
+ entity: (entity, options) => {
584
+ const declared = entity.members ?? entity.fields;
585
+ const fields = declared === void 0 ? void 0 : new Set(Object.keys(declared));
586
+ const unserved = (options.shared ?? []).filter((field) => fields !== void 0 && !fields.has(field));
587
+ if (unserved.length > 0) throw new Error(`[foldkit-remote-server] ${entity.name}'s shared fields name no member: ${unserved.join(", ")}`);
588
+ return {
589
+ entity: entity.name,
590
+ ...fields === void 0 ? {} : { fields },
591
+ read: options.read,
592
+ ...options.authorize === void 0 ? {} : { authorize: options.authorize },
593
+ ...options.filter === void 0 ? {} : { filter: options.filter },
594
+ ...options.shared === void 0 ? {} : { shared: new Set(options.shared) }
595
+ };
596
+ },
597
+ mutation: (mutation, run) => ({
598
+ mutation: mutation.name,
599
+ Input: mutation.Input,
600
+ Output: mutation.Output,
601
+ Refusal: mutation.Refusal,
602
+ run: (context) => run({
603
+ input: context.input,
604
+ principal: context.principal,
605
+ requestId: context.requestId
606
+ }).pipe(Effect.map((outcome) => ({
607
+ output: outcome.output,
608
+ entities: outcome.entities ?? [],
609
+ connections: outcome.connections ?? [],
610
+ deleted: outcome.deleted ?? []
611
+ })))
612
+ }),
613
+ /**
614
+ * A refusal of `mutation`, as a value of its declared `Refusal`: fail a
615
+ * Source with it (`yield* RemoteServer.refuse(SavePost, { _tag: 'Field', ... })`)
616
+ * and the client reads it, decoded, with `Data.refusal`. `message` is what a
617
+ * person reads, beside it.
618
+ */
619
+ refuse: (mutation, refusal, message = `Mutation ${mutation.name} was refused`) => new MutationRefused({
620
+ mutation: mutation.name,
621
+ refusal,
622
+ message
623
+ }),
624
+ /**
625
+ * A refusal of who is asking: fail a Source with it
626
+ * (`yield* RemoteServer.forbid()`) and the write never runs. `reason`, when
627
+ * given, is what the person who asked reads; without it the refusal says
628
+ * nothing of why. `answer` sends it as a 403, and the client's mutation
629
+ * fails with `_tag: 'Forbidden'`.
630
+ */
631
+ forbid: (reason) => new RemoteForbidden({
632
+ message: reason ?? "Forbidden",
633
+ ...reason === void 0 ? {} : { reason }
634
+ }),
635
+ /**
636
+ * A refusal of a caller who could not be told: a `serveFetch` or
637
+ * `defineDocumentHost` resolver fails with it (`RemoteServer.unauthenticated()`)
638
+ * when the credential it was sent no longer holds. It answers 401, with
639
+ * `reason`, when given, for the person who asked.
640
+ */
641
+ unauthenticated: (reason) => new RemoteUnauthenticated({
642
+ message: reason ?? "Unauthenticated",
643
+ ...reason === void 0 ? {} : { reason }
644
+ }),
645
+ /**
646
+ * The Source of a mutation that is a declared `Write`, with no handler: the
647
+ * input bound to the write lands through `writer`, and the row as written
648
+ * answers as a patch (a deletion as `deleted`). An update writes only the
649
+ * keys the client named, when it named some, and fails for a row that is not
650
+ * there; an insert of an id already holding what it writes (a retry)
651
+ * answers with that row, and of one holding anything else fails; a delete of
652
+ * a row already gone succeeds. A row that moved past the revision the write
653
+ * `expect`s is refused as a conflict.
654
+ */
655
+ write: (mutation, writer) => {
656
+ const { write } = mutation;
657
+ if (write.input.entity.name !== writer.entity) throw new Error(`[foldkit-remote-server] write "${mutation.name}" writes ${write.input.entity.name}, but its writer is for ${writer.entity}`);
658
+ return {
659
+ mutation: mutation.name,
660
+ writes: {
661
+ entity: writer.entity,
662
+ writer
663
+ },
664
+ Input: mutation.Input,
665
+ Output: mutation.Output,
666
+ Refusal: mutation.Refusal,
667
+ run: ({ input, principal, keys }) => {
668
+ const given = input;
669
+ const expect = Write.expected(write, given);
670
+ const conflict = (bound) => RemoteServer.refuse(mutation, { _tag: "Conflict" }, `${bound.entity} ${bound.id} changed since it was read`);
671
+ const answered = (bound, values) => {
672
+ const read = writer.read;
673
+ const shown = read === void 0 ? Effect.succeed(Option.some(values)) : read({
674
+ id: bound.id,
675
+ fields: Object.keys(values),
676
+ principal
677
+ });
678
+ return Effect.map(shown, Option.match({
679
+ onNone: () => ({
680
+ output: {},
681
+ entities: [],
682
+ connections: [],
683
+ deleted: [{
684
+ entity: bound.entity,
685
+ id: bound.id
686
+ }]
687
+ }),
688
+ onSome: (seen) => ({
689
+ output: {},
690
+ entities: [{
691
+ entity: bound.entity,
692
+ id: bound.id,
693
+ values: seen
694
+ }],
695
+ connections: [],
696
+ deleted: []
697
+ })
698
+ }));
699
+ };
700
+ return Match.value(write).pipe(Match.tagsExhaustive({
701
+ Update: () => Effect.gen(function* () {
702
+ const bound = Write.bind(write, given, keys);
703
+ const written = yield* writer.update({
704
+ id: bound.id,
705
+ values: bound.values,
706
+ links: bound.links,
707
+ expect,
708
+ principal
709
+ });
710
+ if (Option.isSome(written)) return yield* answered(bound, written.value);
711
+ return yield* Option.isSome(expect) ? Effect.fail(conflict(bound)) : Effect.fail(new RemoteServerError({ message: `No ${bound.entity} ${bound.id} to update` }));
712
+ }),
713
+ Insert: () => Effect.gen(function* () {
714
+ const bound = Write.bind(write, given);
715
+ const row = yield* writer.insert({
716
+ id: bound.id,
717
+ values: bound.values,
718
+ links: bound.links,
719
+ principal
720
+ });
721
+ return yield* answered(bound, row);
722
+ }),
723
+ Delete: () => Effect.gen(function* () {
724
+ const bound = Write.bind(write, given);
725
+ if ((yield* writer.delete({
726
+ id: bound.id,
727
+ expect,
728
+ principal
729
+ })) === "moved") return yield* Effect.fail(conflict(bound));
730
+ return {
731
+ output: {},
732
+ entities: [],
733
+ connections: [],
734
+ deleted: [{
735
+ entity: bound.entity,
736
+ id: bound.id
737
+ }]
738
+ };
739
+ })
740
+ }));
741
+ }
742
+ };
743
+ },
744
+ query: (query, run) => ({
745
+ query: query.name,
746
+ Input: query.Input,
747
+ run: (context) => run({
748
+ input: context.input,
749
+ window: context.window,
750
+ principal: context.principal,
751
+ ...context.select === void 0 ? {} : { select: context.select }
752
+ })
753
+ }),
754
+ /** Streams live entity patches for a client's live requirements. */
755
+ live: (entity, options) => ({
756
+ entity: entity.name,
757
+ subscribe: options.subscribe
758
+ }),
759
+ /**
760
+ * A `LiveHub` over entity sources. Pass it to `handlers` as `live`, and every
761
+ * mutation's answered patches and deletions are published to it; call
762
+ * `hub.changed(ref, fields)` yourself only for a write that is not a
763
+ * mutation (a database trigger, a job). Each subscriber that selects any of
764
+ * those fields receives them, re-read through the entity source under its
765
+ * own principal.
766
+ */
767
+ liveHub,
768
+ make: (config) => ({
769
+ entities: new Map(config.entities.map((source) => [source.entity, source])),
770
+ mutations: new Map((config.mutations ?? []).map((source) => [source.mutation, source])),
771
+ queries: new Map((config.queries ?? []).map((source) => [source.query, source])),
772
+ live: new Map((config.live ?? []).map((source) => [source.entity, source]))
773
+ }),
774
+ /**
775
+ * Checks every source name against the declared domain, so an undeclared
776
+ * entity/query/mutation fails at startup rather than returning nothing at
777
+ * call time.
778
+ */
779
+ validate: (domain, server) => {
780
+ const assertDeclared = (kind, declared, names) => {
781
+ for (const name of names) if (!declared.has(name)) throw new Error(`RemoteServer: ${kind} "${name}" is not declared in the Remote domain`);
782
+ };
783
+ assertDeclared("entity", domain.registry.entities, server.entities.keys());
784
+ assertDeclared("query", domain.registry.queries, server.queries.keys());
785
+ assertDeclared("mutation", domain.registry.mutations, server.mutations.keys());
786
+ },
787
+ /**
788
+ * Reads entity requirements through the entity sources, level by level,
789
+ * following relations as `FoldkitRemoteRead` does. Shared by the read
790
+ * handler and the query handler's payload: a query page's items are just
791
+ * requirements the page names, so one response carries both.
792
+ */
793
+ readHelper: (server, principal, options, requests) => Effect.gen(function* () {
794
+ const entities = [];
795
+ const settled = /* @__PURE__ */ new Map();
796
+ const settle = (entity, id, fields) => {
797
+ if (fields.length === 0) return;
798
+ const key = `${entity}:${id}`;
799
+ const entry = settled.get(key) ?? {
800
+ entity,
801
+ id,
802
+ fields: /* @__PURE__ */ new Set()
803
+ };
804
+ for (const field of fields) entry.fields.add(field);
805
+ settled.set(key, entry);
806
+ };
807
+ const fetched = /* @__PURE__ */ new Map();
808
+ const fetchedValues = /* @__PURE__ */ new Map();
809
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
810
+ const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY);
811
+ const over = checkIdsPerEntity(requests, maxIds);
812
+ if (over !== void 0) return yield* new RemoteReadError({ message: `Too many "${over}" ids in one read batch` });
813
+ const paged = checkPagesPerRelation(requests);
814
+ if (paged !== void 0) return yield* new RemoteReadError({ message: `Too many pages of "${paged}" in one read` });
815
+ let pending = requests;
816
+ for (let depth = 0; pending.length > 0; depth++) {
817
+ if (depth > maxDepth) return yield* new RemoteReadError({ message: `Nested selection deeper than ${maxDepth} relation levels` });
818
+ const next = [];
819
+ const follow = (values, relations) => {
820
+ for (const [field, relation] of Object.entries(relations)) {
821
+ if (!Object.hasOwn(values, field)) continue;
822
+ for (const ref of refsIn(values[field])) {
823
+ if (ref.entity !== relation.entity) continue;
824
+ const key = `${relation.entity}:${ref.id}`;
825
+ const read = fetched.get(key);
826
+ const fields = relation.fields.filter((name) => read?.has(name) !== true);
827
+ if (fields.length > 0) next.push({
828
+ entity: relation.entity,
829
+ id: ref.id,
830
+ fields,
831
+ ...relation.windows === void 0 ? {} : { windows: relation.windows },
832
+ ...relation.relations === void 0 ? {} : { relations: relation.relations }
833
+ });
834
+ else if (relation.relations !== void 0) follow(fetchedValues.get(key) ?? {}, relation.relations);
835
+ }
836
+ }
837
+ };
838
+ for (const { ids, slice, renames } of groupByEntity(pending)) {
839
+ const name = slice.entity;
840
+ const source = server.entities.get(name);
841
+ if (source === void 0) continue;
842
+ const allowed = allowedFields(source, principal, slice.fields);
843
+ const allowedSet = new Set(allowed);
844
+ const idList = [...ids.keys()];
845
+ for (const [id, asked] of ids) settle(name, id, [...asked].filter((field) => !allowedSet.has(field)).map((field) => renamed(renames, field)));
846
+ if (allowed.length === 0) continue;
847
+ const windows = windowsOf(slice.windows, allowed);
848
+ const records = yield* readFiltered(source, principal, allowed, (fields) => Effect.map(Effect.forEach(Array.from({ length: Math.ceil(idList.length / maxIds) }, (_, chunk) => idList.slice(chunk * maxIds, (chunk + 1) * maxIds)), (chunk) => source.read({
849
+ ids: chunk,
850
+ fields,
851
+ principal,
852
+ ...windows
853
+ })), (chunks) => chunks.flat())).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteReadError({ message: error.message }))));
854
+ for (const record of records) {
855
+ const values = Object.create(null);
856
+ const omitted = [];
857
+ const asked = ids.get(record.id);
858
+ for (const field of allowed) if (Object.hasOwn(record.values, field)) values[renamed(renames, field)] = record.values[field];
859
+ else if (asked?.has(field) === true) omitted.push(renamed(renames, field));
860
+ entities.push({
861
+ entity: name,
862
+ id: record.id,
863
+ values
864
+ });
865
+ settle(name, record.id, omitted);
866
+ const key = `${name}:${record.id}`;
867
+ const known = fetched.get(key) ?? /* @__PURE__ */ new Set();
868
+ for (const field of allowed) known.add(renamed(renames, field));
869
+ fetched.set(key, known);
870
+ fetchedValues.set(key, {
871
+ ...fetchedValues.get(key),
872
+ ...values
873
+ });
874
+ follow(values, slice.relations ?? {});
875
+ }
876
+ }
877
+ pending = next.flatMap((request) => {
878
+ const read = fetched.get(`${request.entity}:${request.id}`);
879
+ const fields = request.fields.filter((field) => read?.has(field) !== true);
880
+ return fields.length === 0 ? [] : [{
881
+ ...request,
882
+ fields
883
+ }];
884
+ });
885
+ }
886
+ return {
887
+ entities,
888
+ settled: [...settled.values()].map((entry) => ({
889
+ ...entry,
890
+ fields: [...entry.fields]
891
+ }))
892
+ };
893
+ }),
894
+ /**
895
+ * Answers one JSON request through `handlers`: what an HTTP endpoint, a
896
+ * worker or a server in the page calls with the body it received, parsed.
897
+ * The request and its payload are decoded by the protocol's own schemas
898
+ * before a handler sees them, so an operation name is one of Remote's three
899
+ * and nothing else. A body that is not a request is a 400; a caller who
900
+ * could not be told a 401; a refusal of who is asking a 403; a handler's
901
+ * failure a 500 with its message; a defect a 500 that says nothing of it.
902
+ * `Remote.json` and `Remote.http` are the other end.
903
+ */
904
+ answer: (handlers, body) => {
905
+ const asked = {
906
+ read: (payload) => Effect.flatMap(Schema.decodeUnknownEffect(ReadBatch)(payload), handlers.FoldkitRemoteRead),
907
+ query: (payload) => Effect.flatMap(Schema.decodeUnknownEffect(QueryRequest)(payload), handlers.FoldkitRemoteQuery),
908
+ mutate: (payload) => Effect.flatMap(Schema.decodeUnknownEffect(MutationRequest)(payload), handlers.FoldkitRemoteMutate)
909
+ };
910
+ return Schema.decodeUnknownEffect(RemoteJsonRequest)(body).pipe(Effect.flatMap(({ operation, payload }) => asked[operation](payload)), Effect.map((result) => ({
911
+ status: 200,
912
+ body: { result }
913
+ })), Effect.catchTag("SchemaError", (error) => Effect.succeed({
914
+ status: 400,
915
+ body: { error: error.message }
916
+ })), Effect.catchTag("Unauthenticated", (error) => Effect.succeed(unauthenticatedAnswer(error))), Effect.catchTag("Forbidden", (error) => Effect.succeed({
917
+ status: 403,
918
+ body: {
919
+ error: error.message,
920
+ forbidden: error.reason === void 0 ? {} : { reason: error.reason }
921
+ }
922
+ })), Effect.catchTag("RemoteMutationError", (error) => Effect.succeed(error.refusal === void 0 ? {
923
+ status: 500,
924
+ body: { error: error.message }
925
+ } : {
926
+ status: 422,
927
+ body: {
928
+ error: error.message,
929
+ refusal: error.refusal
930
+ }
931
+ })), Effect.catch((error) => Effect.succeed({
932
+ status: 500,
933
+ body: { error: error.message }
934
+ })), Effect.catchCause(() => Effect.succeed({
935
+ status: 500,
936
+ body: { error: "Internal error" }
937
+ })));
938
+ },
939
+ /**
940
+ * Compiles the server into Remote's RPC handlers, answering as `principal`:
941
+ * a value, or a Context key (`G.Principal`) read on each call, which
942
+ * authentication provides per request. Unknown entities, entities with no
943
+ * allowed fields, and unknown mutations return an error or nothing rather
944
+ * than leaking existence.
945
+ */
946
+ handlers: (server, principal, options = {}) => {
947
+ const asking = Context.isKey(principal) ? principal : Effect.succeed(principal);
948
+ return {
949
+ FoldkitRemoteRead: Effect.fn("RemoteServer.FoldkitRemoteRead")(function* (payload) {
950
+ const mismatch = protocolMismatch(payload.version);
951
+ if (mismatch !== void 0) return yield* mismatch;
952
+ const caller = yield* asking;
953
+ return yield* RemoteServer.readHelper(server, caller, options, payload.requests);
954
+ }),
955
+ FoldkitRemoteMutate: Effect.fn("RemoteServer.FoldkitRemoteMutate")(function* (payload) {
956
+ const source = server.mutations.get(payload.mutation);
957
+ if (source === void 0) return yield* new RemoteMutationError({ message: `Unknown mutation: ${payload.mutation}` });
958
+ const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation input" }))));
959
+ const caller = yield* asking;
960
+ const outcome = yield* source.run({
961
+ input,
962
+ principal: caller,
963
+ requestId: payload.requestId,
964
+ keys: payload.keys
965
+ }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteMutationError({ message: error.message }))), Effect.catchTag("MutationRefused", (refused) => refusalError(source.Refusal, payload.mutation, refused)));
966
+ const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteMutationError({ message: "Invalid mutation output" }))));
967
+ const hub = options.live;
968
+ if (hub !== void 0) {
969
+ const stored = source.writes !== void 0;
970
+ yield* Effect.forEach(outcome.entities, (patch) => hub.changed({
971
+ entity: patch.entity,
972
+ id: patch.id
973
+ }, 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)));
974
+ }
975
+ return {
976
+ output,
977
+ entities: outcome.entities.map((patch) => ({
978
+ entity: patch.entity,
979
+ id: patch.id,
980
+ values: patch.values
981
+ })),
982
+ connections: outcome.connections,
983
+ deleted: outcome.deleted.map((gone) => ({
984
+ entity: gone.entity,
985
+ id: gone.id
986
+ }))
987
+ };
988
+ }),
989
+ FoldkitRemoteQuery: Effect.fn("RemoteServer.FoldkitRemoteQuery")(function* (payload) {
990
+ const source = server.queries.get(payload.query);
991
+ if (source === void 0) return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` });
992
+ const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(Effect.catchTag("SchemaError", () => Effect.fail(new RemoteQueryError({ message: "Invalid query input" }))));
993
+ const select = payload.select;
994
+ if (select !== void 0) {
995
+ const paged = checkPagesPerRelation([select]);
996
+ if (paged !== void 0) return yield* new RemoteQueryError({ message: `Too many pages of "${paged}" in one query select` });
997
+ }
998
+ const caller = yield* asking;
999
+ const page = yield* source.run({
1000
+ input,
1001
+ window: payload.window,
1002
+ principal: caller,
1003
+ ...select === void 0 ? {} : { select }
1004
+ }).pipe(Effect.catchTag("RemoteServerError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
1005
+ if (select === void 0) return {
1006
+ edges: page.edges,
1007
+ start: page.start,
1008
+ end: page.end
1009
+ };
1010
+ const requirements = page.edges.flatMap((edge) => edge.entity === select.entity ? [{
1011
+ entity: select.entity,
1012
+ id: edge.id,
1013
+ fields: [...select.fields],
1014
+ ...select.windows === void 0 ? {} : { windows: select.windows },
1015
+ ...select.relations === void 0 ? {} : { relations: select.relations }
1016
+ }] : []);
1017
+ if (requirements.length === 0) return {
1018
+ edges: page.edges,
1019
+ start: page.start,
1020
+ end: page.end,
1021
+ entities: [],
1022
+ settled: []
1023
+ };
1024
+ const read = yield* RemoteServer.readHelper(server, caller, options, requirements).pipe(Effect.catchTag("RemoteReadError", (error) => Effect.fail(new RemoteQueryError({ message: error.message }))));
1025
+ return {
1026
+ edges: page.edges,
1027
+ start: page.start,
1028
+ end: page.end,
1029
+ ...read
1030
+ };
1031
+ }),
1032
+ FoldkitRemoteLive: (payload) => {
1033
+ const mismatch = protocolMismatch(payload.version);
1034
+ if (mismatch !== void 0) return Stream.fail(mismatch);
1035
+ return Stream.unwrap(Effect.map(asking, (caller) => {
1036
+ const streams = [...new Set(payload.requirements.map((request) => request.entity))].flatMap((entity) => {
1037
+ const source = server.live.get(entity);
1038
+ if (source === void 0) return [];
1039
+ return [source.subscribe({
1040
+ requirements: payload.requirements.filter((request) => request.entity === entity),
1041
+ after: payload.after,
1042
+ principal: caller
1043
+ })];
1044
+ });
1045
+ if (options.live !== void 0) streams.push(options.live.subscribe({
1046
+ requirements: payload.requirements,
1047
+ after: payload.after,
1048
+ principal: caller,
1049
+ maxIdsPerEntity: options.maxIdsPerEntity
1050
+ }));
1051
+ return Stream.mergeAll(streams, { concurrency: "unbounded" }).pipe(Stream.mapError((error) => new RemoteLiveError({ message: error.message })));
1052
+ }));
1053
+ }
1054
+ };
1055
+ }
1056
+ };
1057
+ //#endregion
1058
+ export { assertSupported as a, unauthenticatedAnswer as c, QueryEvaluateError as i, RemoteServer as n, evaluate$1 as o, RemoteServerError as r, supported as s, MutationRefused as t };
1059
+
1060
+ //# sourceMappingURL=src-DKYZjLc7.mjs.map