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