foldkit-remote-server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,20 +1,69 @@
1
1
  # `foldkit-remote-server`
2
2
 
3
- Answers the requests a
4
- [`foldkit-remote`](https://github.com/doeixd/foldkit-plus/tree/main/packages/remote)
5
- client makes. You write one **Source** per entity, query, and mutation — plain
6
- Effect functions that load rows — and this package compiles them into the
7
- `RemoteRpc` handlers: it groups and de-duplicates the ids a client asked for,
8
- drops the fields a principal may not read, resolves a nested selection level by
9
- level through each entity's own Source, and normalizes the results into the
10
- patches the client's store reconciles.
11
-
12
- Reach for it when the server is yours and you want the client's field-level
13
- selections honoured end to end, with authorization enforced where the field
14
- names are still known rather than in the view. It owns no HTTP, WebSockets,
15
- serialization, authentication protocol, or database connection: `principal` is
16
- resolved outside and passed in, and a Source's database is an Effect requirement
17
- the Source declares, not something this package holds.
3
+ The server-side interpreter for [`foldkit-remote`](../remote).
4
+
5
+ A Remote client sends **semantic requirements** — entity ids, selected fields,
6
+ query windows, mutations, and live requirements. `foldkit-remote-server` turns
7
+ those requirements into calls to application-owned **Sources**, enforces
8
+ field-level read authorization while the field names are still known, and
9
+ normalizes the results back into the patches the client cache understands.
10
+
11
+ The central pipeline is:
12
+
13
+ ```text
14
+ Remote requirement
15
+ |
16
+ v
17
+ RemoteServer handlers
18
+ |
19
+ +-- validate protocol / input
20
+ +-- filter fields by Entity + principal
21
+ +-- group and de-duplicate reads
22
+ |
23
+ v
24
+ application Source
25
+ |
26
+ v
27
+ normalized Remote result
28
+ |
29
+ v
30
+ Remote client -> Message -> Data.reduce -> Model
31
+ ```
32
+
33
+ A Source is deliberately small: it says how your application reads one Entity,
34
+ runs one Query or Mutation, or produces one live stream. The package does **not**
35
+ own HTTP, WebSockets, authentication, or a database connection. Authentication
36
+ resolves a `principal` outside this package; database/API clients remain Effect
37
+ requirements of the Sources that use them.
38
+
39
+ Use this package when the server is yours and you want the selections declared
40
+ by `foldkit-remote` to survive all the way to the data boundary instead of
41
+ turning back into hand-written per-screen endpoints.
42
+
43
+ ## What this package owns
44
+
45
+ ```text
46
+ client owns
47
+ which server facts are required
48
+
49
+ foldkit-remote-server owns
50
+ requirement interpretation
51
+ field authorization
52
+ read grouping / de-duplication
53
+ nested selection traversal
54
+ normalized wire results
55
+
56
+ application Sources own
57
+ how those facts are actually loaded or changed
58
+
59
+ Effect RPC / application owns
60
+ transport + serialization + authentication
61
+ ```
62
+
63
+ That separation matters. `RemoteServer` can decide that a client may read
64
+ `Project.name` but not `Project.privateNotes`; only your Source knows whether
65
+ that field comes from Postgres, another service, an in-memory index, or
66
+ something else.
18
67
 
19
68
  ## Install
20
69
 
@@ -22,229 +71,466 @@ the Source declares, not something this package holds.
22
71
  pnpm add foldkit-remote-server
23
72
  ```
24
73
 
25
- `effect` is a peer dependency; `foldkit-remote` and `foldkit-surface` come with
26
- it. `foldkit-remote-drizzle` compiles its selections and queries to SQL.
74
+ `effect` is a peer dependency; `foldkit-remote` comes with the package.
75
+ [`foldkit-remote-drizzle`](../remote-drizzle) is an optional Source compiler for
76
+ Drizzle-backed entities and queries.
27
77
 
28
- ## Quick start
78
+ ## Sixty seconds: answer one Entity read
29
79
 
30
- One entity, one mutation, one query, one live stream, compiled to a layer.
31
- `loadProjects`, `renameProject`, `projectsPage`, and `projectEvents` are the
32
- application's own data access; `principal` is whatever authentication resolved.
80
+ Start with the same Entity the client selects:
33
81
 
34
82
  ```ts
35
- import { Effect, Schema } from 'effect'
36
- import { Entity, Mutation, Query, RemoteRpc } from 'foldkit-remote'
83
+ import { Schema } from 'effect'
84
+ import { Entity, Remote, RemoteRpc } from 'foldkit-remote'
37
85
  import { RemoteServer } from 'foldkit-remote-server'
38
86
 
39
87
  const Project = Entity.make(
40
88
  'Project',
41
- Schema.Struct({ id: Schema.String, name: Schema.String, privateNotes: Schema.String }),
89
+ Schema.Struct({
90
+ id: Schema.String,
91
+ name: Schema.String,
92
+ privateNotes: Schema.String,
93
+ }),
42
94
  )
95
+ ```
43
96
 
44
- const RenameProject = Mutation.make('RenameProject', {
45
- Input: Schema.Struct({ id: Schema.String, name: Schema.String }),
46
- Output: Schema.Struct({ id: Schema.String }),
47
- })
97
+ Give that Entity one Source:
48
98
 
49
- const ProjectsByOwner = Query.make('ProjectsByOwner', {
50
- Input: Schema.Struct({ ownerId: Schema.String }),
51
- Result: Query.connection(Project),
99
+ ```ts
100
+ const ProjectSource = RemoteServer.entity(Project, {
101
+ // Authentication already resolved `principal` before RemoteServer sees it.
102
+ // Return only fields this caller may read.
103
+ authorize: (principal, fields) =>
104
+ fields.filter(field => field !== 'privateNotes' || principal.isAdmin),
105
+
106
+ // Your application owns this function. Read exactly the ids/fields requested.
107
+ read: ({ ids, fields, principal }) =>
108
+ loadProjects({ ids, fields, principal }),
52
109
  })
53
110
 
54
111
  const Server = RemoteServer.make({
55
- entities: [
56
- RemoteServer.entity(Project, {
57
- authorize: (principal, fields) => fields.filter(field => principal.canRead(Project, field)),
58
- read: ({ ids, fields, windows, principal }) => loadProjects({ ids, fields, windows, principal }),
59
- }),
60
- ],
61
- mutations: [
62
- RemoteServer.mutation(RenameProject, ({ input, principal }) =>
63
- renameProject(input, principal).pipe(
64
- Effect.map(output => ({
65
- output,
66
- entities: [Entity.patch(Project.ref(input.id), { name: input.name })],
67
- })),
68
- ),
69
- ),
70
- ],
71
- queries: [
72
- RemoteServer.query(ProjectsByOwner, ({ input, window, principal }) =>
73
- projectsPage({ ownerId: input.ownerId, window, principal }),
74
- ),
75
- ],
76
- live: [
77
- RemoteServer.live(Project, {
78
- subscribe: ({ requirements, after, principal }) =>
79
- projectEvents({ ids: requirements.map(request => request.id), after, principal }),
80
- }),
81
- ],
112
+ entities: [ProjectSource],
82
113
  })
114
+ ```
115
+
116
+ Compile that definition into the Remote RPC handlers for one authenticated
117
+ principal:
83
118
 
119
+ ```ts
84
120
  const handlers = RemoteServer.handlers(Server, principal)
85
121
  const layer = RemoteRpc.toLayer(handlers)
86
- // FoldkitRemoteRead, FoldkitRemoteMutate, FoldkitRemoteQuery, FoldkitRemoteLive
87
122
  ```
88
123
 
89
- `handlers(server, principal, options?)` takes a `HandlerOptions<P, R>`:
90
- `maxIdsPerEntity` (default 1000) bounds how many distinct ids of one entity a
91
- read batch — or a `liveHub` subscription — may name, `maxDepth` (default 8)
92
- bounds nested resolution, and `live` is the hub whose signals reach the
93
- subscriptions this handler registers. In-process, the handlers are a
94
- `RemoteClient` through `Remote.clientLayer(handlers)`, with whatever the sources
95
- require supplied by `Layer.provide`.
124
+ That is the core package. A client requirement such as:
96
125
 
97
- ## Sources
126
+ ```text
127
+ Project:p1 [id, name, privateNotes]
128
+ ```
98
129
 
99
- ### `RemoteServer.entity`
130
+ runs as:
100
131
 
101
132
  ```text
102
- RemoteServer.entity(entity, {
103
- read: (context: { ids: readonly string[]; fields: readonly string[]
104
- windows?: Record<string, QueryWindow>; principal: P })
105
- => Effect<ReadonlyArray<{ id: string; values: Record<string, unknown> }>, RemoteServerError, R>
106
- authorize?: (principal: P, fields: readonly string[]) => readonly string[]
107
- }): EntitySource<P, R>
133
+ 1. Project declares: id, name, privateNotes
134
+ 2. authorize returns: id, name
135
+ 3. Source receives: ids=[p1], fields=[id,name]
136
+ 4. Source returns: { id: 'p1', values: { id: 'p1', name: 'Apollo' } }
137
+ 5. handler normalizes: Project:p1 { id, name }
138
+ 6. client records presence only for the returned fields
108
139
  ```
109
140
 
110
- Given the Entity, a request for a field it does not declare never reaches
111
- `read` or `authorize`; `RemoteServer.entity({ name: 'Project' }, …)` declares
112
- no fields and passes every requested one through.
141
+ `privateNotes` never reaches `read`. Authorization happens before application
142
+ data access, while the request still has semantic field names.
113
143
 
114
- `read` is called once per entity, id batch, and window per read level: ids are
115
- batched up to `maxIdsPerEntity`, ids that page a relation differently are read
116
- separately, and a nested selection reads its next level after the refs arrive.
117
- `windows` carries the pagination window for each requested relation field. The
118
- result may be a partial entity: a field the source omits is simply not present,
119
- and presence metadata on the client reflects that.
144
+ ## The read lifecycle
120
145
 
121
- ### `RemoteServer.query`
146
+ An Entity read is more than a direct function call because a Remote selection
147
+ may contain several ids and nested relations. The handler performs the mechanical
148
+ work once so Sources do not have to:
122
149
 
123
150
  ```text
124
- RemoteServer.query(query, (context: { input: Input; window: QueryWindow; principal: P })
125
- => Effect<QueryPage, RemoteServerError, R>): QuerySource<P, R>
151
+ client requirements
152
+ |
153
+ v
154
+ group by Entity
155
+ |
156
+ v
157
+ union requested fields
158
+ |
159
+ v
160
+ filter declared + authorized fields
161
+ |
162
+ v
163
+ batch / de-duplicate ids
164
+ |
165
+ v
166
+ Entity Source.read(...)
167
+ |
168
+ v
169
+ follow selected relation refs
170
+ |
171
+ v
172
+ next Entity Source
173
+ |
174
+ v
175
+ normalized patches
126
176
  ```
127
177
 
128
- `QueryPage` is `{ edges, start, end }`; `start`/`end` are `Boundary` values
129
- (`Terminal`, `Cursor`, or `Unknown`) so the client can merge the page without
130
- inferring adjacency from row count.
178
+ A Source therefore receives the useful boundary directly:
131
179
 
132
- ### `RemoteServer.mutation`
180
+ ```text
181
+ RemoteServer.entity(entity, {
182
+ read: ({ ids, fields, windows?, principal }) => Effect<
183
+ ReadonlyArray<{ id: string; values: Record<string, unknown> }>,
184
+ RemoteServerError,
185
+ R
186
+ >,
187
+
188
+ authorize?: (principal, fields) => readonly string[]
189
+ })
190
+ ```
191
+
192
+ Important consequences:
193
+
194
+ - a field the Entity does not declare never reaches `authorize` or `read`;
195
+ - `authorize` can only remove requested fields, never add new ones;
196
+ - a Source may return a partial entity — omitted fields remain absent on the
197
+ client and may be requested later;
198
+ - ids shared by several selections are de-duplicated;
199
+ - relation targets are fetched level by level and shared targets are not loaded
200
+ repeatedly;
201
+ - a relation the principal may not read is never followed.
202
+
203
+ The Source should still avoid reading or returning columns the request did not
204
+ ask for. The handler filters returned values again, but the data boundary is the
205
+ best place to preserve least privilege and avoid wasted work.
206
+
207
+ ## Nested selections
208
+
209
+ Suppose the client projects:
133
210
 
134
211
  ```text
135
- RemoteServer.mutation(mutation, (context: { input: Input; principal: P })
136
- => Effect<{ output: Output
137
- entities?: ReadonlyArray<NormalizedPatch>
138
- connections?: ReadonlyArray<ConnectionChange> },
139
- RemoteServerError, R>): MutationSource<P, R>
212
+ Project:p1 {
213
+ id
214
+ name
215
+ owner { id name }
216
+ }
140
217
  ```
141
218
 
142
- `input` is decoded against the mutation's `Input` schema first, so the callback
143
- receives the typed input. `output` is encoded against `Output`; `entities` are
144
- the normalized cache patches the client will reconcile, and `connections` the
145
- confirmed connection inserts and removes that replace the client's optimistic
146
- ones in place: `RemoteServer.prepend(connection, ref)`, `append`, and
147
- `remove`, where `connection` is a `QueryRef` or its identity.
219
+ and the Project Source returns an owner ref:
148
220
 
149
- ### `RemoteServer.live`
221
+ ```text
222
+ Project:p1.owner = User:u7
223
+ ```
224
+
225
+ The handler follows that ref through the `User` Source on the next level:
150
226
 
151
227
  ```text
152
- RemoteServer.live(entity, {
153
- subscribe: (context: { requirements: ReadonlyArray<Requirement>; after: number; principal: P })
154
- => Stream<LiveChange, RemoteServerError, R>
155
- }): LiveSource<P, R>
228
+ Project requirement
229
+ |
230
+ v
231
+ Project Source
232
+ |
233
+ | owner = User:u7
234
+ v
235
+ User requirement
236
+ |
237
+ v
238
+ User Source
239
+ ```
240
+
241
+ The Sources do not recursively call each other. `RemoteServer` owns traversal,
242
+ depth limits, batching, and de-duplication; each Source still answers only for
243
+ its own Entity.
244
+
245
+ ## Queries
246
+
247
+ A Query Source answers the ordered connection itself. Entity fields for the page
248
+ items remain normal Entity reads, so query membership and entity data stay
249
+ separate:
250
+
251
+ ```ts
252
+ import { Query } from 'foldkit-remote'
253
+
254
+ const ProjectsByOwner = Query.make('ProjectsByOwner', {
255
+ Input: Schema.Struct({ ownerId: Schema.String }),
256
+ Result: Query.connection(Project),
257
+ })
258
+
259
+ const ProjectsByOwnerSource = RemoteServer.query(
260
+ ProjectsByOwner,
261
+ ({ input, window, principal }) =>
262
+ projectsPage({ ownerId: input.ownerId, window, principal }),
263
+ )
264
+
265
+ const Server = RemoteServer.make({
266
+ entities: [ProjectSource],
267
+ queries: [ProjectsByOwnerSource],
268
+ })
156
269
  ```
157
270
 
158
- `after` is the client's resume cursor; events at or before it are duplicates. The
159
- handler merges the requested entities' streams and maps a source failure onto the
160
- wire error. An entity with no live source contributes nothing, so the client
161
- plans a refetch instead of failing the stream. A `LiveChange` is an entity patch
162
- or delete, or a connection insert/remove/invalidate.
271
+ A Query returns:
272
+
273
+ ```ts
274
+ {
275
+ edges,
276
+ start,
277
+ end,
278
+ }
279
+ ```
280
+
281
+ `start` and `end` are Remote `Boundary` values (`Terminal`, `Cursor`, or
282
+ `Unknown`). The client uses those explicit boundaries when merging pages instead
283
+ of guessing from row count.
284
+
285
+ Query input is decoded through the Query's own Schema before your callback runs.
286
+ The callback receives the decoded input, the requested `QueryWindow`, and the
287
+ principal.
163
288
 
164
- ### `RemoteServer.liveHub`
289
+ ## Mutations
165
290
 
166
- The higher-level signal. A hub tracks each live subscriber's requirements and
167
- principal, so the server says *what changed* and the hub works out *who cares*:
291
+ A Mutation Source changes server-owned state. It returns the protocol output
292
+ plus any normalized entity/connection changes that should settle the client's
293
+ cache immediately:
168
294
 
169
295
  ```ts
170
- // `entitySources` is the same array `RemoteServer.make({ entities })` was given.
296
+ import { Effect } from 'effect'
297
+ import { Mutation } from 'foldkit-remote'
298
+
299
+ const RenameProject = Mutation.make('RenameProject', {
300
+ Input: Schema.Struct({ id: Schema.String, name: Schema.String }),
301
+ Output: Schema.Struct({ id: Schema.String }),
302
+ })
303
+
304
+ const RenameProjectSource = RemoteServer.mutation(
305
+ RenameProject,
306
+ ({ input, principal }) =>
307
+ renameProject(input, principal).pipe(
308
+ Effect.map(output => ({
309
+ output,
310
+ entities: [
311
+ Entity.patch(Project.ref(input.id), { name: input.name }),
312
+ ],
313
+ })),
314
+ ),
315
+ )
316
+ ```
317
+
318
+ The input is decoded before the Source runs and the output is encoded before it
319
+ crosses the wire. A Source may additionally return connection changes:
320
+
321
+ ```ts
322
+ RemoteServer.prepend(connection, Project.ref(id))
323
+ RemoteServer.append(connection, Project.ref(id))
324
+ RemoteServer.remove(connection, Project.ref(id))
325
+ ```
326
+
327
+ Those confirmed changes replace the corresponding optimistic connection layers
328
+ on the client.
329
+
330
+ Remote mutations are immediate requests against **server-owned** state. They are
331
+ not a durable offline intent log; client-authored edits that must survive offline
332
+ belong to `foldkit-sync`.
333
+
334
+ ## Live data
335
+
336
+ There are two ways to produce live changes.
337
+
338
+ ### Write a live Source directly
339
+
340
+ ```ts
341
+ const ProjectLive = RemoteServer.live(Project, {
342
+ subscribe: ({ requirements, after, principal }) =>
343
+ projectEvents({
344
+ requirements,
345
+ after,
346
+ principal,
347
+ }),
348
+ })
349
+ ```
350
+
351
+ `after` is the client's resume cursor. Events at or before it are duplicates.
352
+ The stream carries Remote `LiveChange`s: entity patches/deletes and connection
353
+ insert/remove/invalidate events.
354
+
355
+ If an Entity has no live Source, it contributes no stream. That is not an error:
356
+ the client planner can fall back to refetching it.
357
+
358
+ ### Let a `liveHub` re-read changed fields
359
+
360
+ When your infrastructure can say **what changed** but does not naturally produce
361
+ Remote patches, use a hub:
362
+
363
+ ```ts
364
+ const entitySources = [ProjectSource]
171
365
  const hub = yield* RemoteServer.liveHub(entitySources)
172
- const handlers = RemoteServer.handlers(Server, principal, { live: hub })
173
366
 
174
- // Wherever the data changes (a mutation source, a database trigger):
367
+ const handlers = RemoteServer.handlers(Server, principal, {
368
+ live: hub,
369
+ })
370
+
371
+ // From a mutation Source, database trigger consumer, etc.
175
372
  yield* hub.changed(Project.ref(projectId), ['status', 'updatedAt'])
176
373
  yield* hub.deleted(Project.ref(projectId))
177
374
  ```
178
375
 
179
- `liveHub` and its signals are Effects, so the lines above live inside an
180
- `Effect.gen`. It needs only the entity sources, so the mutation sources that
181
- signal it can be built after it.
182
-
183
- `changed` intersects the fields with what each subscriber selects, re-reads
184
- that intersection through the entity's own source under the subscriber's
185
- principal (one read per principal value and window signature; subscribers
186
- selecting none of the fields do no work), and streams an `EntityPatched`
187
- carrying only the fields that subscriber may see. A record the source does not
188
- return for the changed id reaches nobody. `deleted` streams an `EntityDeleted`
189
- to the entity's subscribers. Cursors continue from the cursor each subscriber resumed at, so
190
- the client's duplicate and gap handling is unchanged. A hub and hand-written
191
- `RemoteServer.live` sources number their events independently; use one or the
192
- other for a given subscription. Nested relation targets are not subscribed by
193
- the hub, only the requirements' own entities.
194
-
195
- ## Authorization
196
-
197
- Authentication and authorization are separate. Authentication answers *who is
198
- this* (Effect RPC middleware → `Principal`); `RemoteServer` answers *may this
199
- principal read this semantic field*. Authorization is mandatory, not opt-in:
200
-
201
- - A field the Entity does not declare is dropped before `authorize` sees it.
202
- - An entity with no `authorize` exposes the requested fields.
203
- - An entity with `authorize` exposes only the returned fields, and a field the
204
- principal may not see is dropped.
205
- - **Never read or return a field the client did not request**, even if a
206
- permissive `authorize` allows more.
207
- - If no field survives authorization, the entity contributes nothing, so the
208
- existence of an unauthorized entity is not leaked.
376
+ The hub remembers each subscriber's requirements and principal. `changed`:
377
+
378
+ 1. intersects the changed fields with what each subscriber selected;
379
+ 2. re-reads only that intersection through the Entity Source;
380
+ 3. applies that subscriber's authorization again;
381
+ 4. emits the resulting patch with a continuing cursor.
382
+
383
+ Subscribers that selected none of the changed fields do no work.
384
+
385
+ A hand-written live Source and a hub number their events independently. Use one
386
+ or the other for a given subscription path rather than mixing cursor domains.
387
+
388
+ ## Authentication vs authorization
389
+
390
+ Keep these boundaries separate:
391
+
392
+ ```text
393
+ authentication
394
+ "Who is making this request?"
395
+ Effect RPC middleware / application
396
+ |
397
+ v
398
+ Principal
399
+ |
400
+ v
401
+ authorization
402
+ "Which semantic fields may this principal read?"
403
+ RemoteServer.entity(... authorize ...)
404
+ ```
405
+
406
+ `RemoteServer.handlers(Server, principal)` deliberately receives a resolved
407
+ principal. It does not inspect headers, sessions, cookies, or bearer tokens.
408
+
409
+ For Entity reads:
410
+
411
+ - undeclared fields are dropped first;
412
+ - `authorize` receives only declared, requested fields;
413
+ - omitting `authorize` means the requested declared fields are readable;
414
+ - returning no fields produces no entity contribution;
415
+ - existence is not leaked merely because an unauthorized id was requested.
416
+
417
+ Mutation and Query policy belongs in their Sources because those operations are
418
+ application-specific rather than field-selection policy.
419
+
420
+ ## Compose and validate the server
421
+
422
+ A complete server definition is just the collection of Sources:
423
+
424
+ ```ts
425
+ const Server = RemoteServer.make({
426
+ entities: [ProjectSource, UserSource],
427
+ queries: [ProjectsByOwnerSource],
428
+ mutations: [RenameProjectSource],
429
+ live: [ProjectLive],
430
+ })
431
+ ```
432
+
433
+ When the client and server share the Remote domain declaration, validate the
434
+ Source names at startup:
435
+
436
+ ```ts
437
+ const Data = Remote.define({
438
+ entities: [Project, User],
439
+ queries: [ProjectsByOwner],
440
+ mutations: [RenameProject],
441
+ })
442
+
443
+ RemoteServer.validate(Data, Server)
444
+ ```
445
+
446
+ That catches an Entity, Query, or Mutation Source whose name is not declared by
447
+ the shared domain instead of letting it silently answer nothing at runtime.
448
+
449
+ Then compile once per authenticated principal:
450
+
451
+ ```ts
452
+ const handlers = RemoteServer.handlers(Server, principal, {
453
+ maxIdsPerEntity: 1000,
454
+ maxDepth: 8,
455
+ live: hub,
456
+ })
457
+ ```
458
+
459
+ `handlers` implements the `RemoteRpc` client shape directly. In-process — tests,
460
+ SSR, a worker, or a single service — it can become a `RemoteClient` with:
461
+
462
+ ```ts
463
+ const clientLayer = Remote.clientLayer(handlers)
464
+ ```
465
+
466
+ Across a process boundary, use:
467
+
468
+ ```ts
469
+ const rpcLayer = RemoteRpc.toLayer(handlers)
470
+ ```
471
+
472
+ The application supplies the Effect RPC server/transport layer. `RemoteServer`
473
+ does not choose HTTP, WebSocket, or another transport for you.
474
+
475
+ ## Runtime dependencies belong to Sources
476
+
477
+ Sources are Effects, so dependencies stay explicit:
478
+
479
+ ```text
480
+ Project Source
481
+ requires Database
482
+
483
+ Billing Query Source
484
+ requires BillingApi
485
+
486
+ RemoteServer
487
+ requires Database | BillingApi
488
+ ```
489
+
490
+ The server definition does not capture either service. Provide their Layers at
491
+ the application boundary. This is also why `foldkit-remote-drizzle` provides
492
+ Drizzle-backed Sources rather than putting a database inside `RemoteServer`.
209
493
 
210
494
  ## Hardening
211
495
 
212
- - A read batch is bounded per entity (`maxIdsPerEntity`, default 1000, counted
213
- across the batch's window groups) and an oversized one fails rather than
214
- loading unbounded rows; a `liveHub` subscription is bounded the same way. A
215
- hand-written `RemoteServer.live` source bounds itself.
216
- - A selection nested past `MAX_RELATION_DEPTH` (8) or naming more than
217
- `MAX_FIELDS_PER_REQUEST` (256) fields of one entity is refused at decode.
218
- - Returned field names are filtered with `Object.hasOwn` and accumulated into a
219
- null-prototype object, so a crafted field name such as `__proto__` or
220
- `toString` cannot reach the prototype.
221
- - Handler errors are remapped to the wire error types without echoing internals.
222
-
223
- ## What it owns
224
-
225
- - Entity, query, mutation, and live Sources.
226
- - Selection authorization and field filtering.
227
- - Request grouping, id de-duplication, field unions, and window threading.
228
- - Normalization of source results into wire entities.
229
- - Source-name validation: `RemoteServer.validate(domain, server)` checks every
230
- entity, query, and mutation source against the domain's `registry`, so an
231
- undeclared name fails at startup rather than returning nothing at call time.
232
- - Compilation to the `RemoteRpc` handlers.
233
-
234
- ## Limits
235
-
236
- - Transport, serialization, and the authentication protocol are Effect RPC's; the
237
- application provides the server protocol layer.
238
- - The live wire carries a `LiveChange` union: entity patches and deletes, plus
239
- connection insert/remove/invalidate events.
240
- - Database and other runtime dependencies are the Source's Effect requirements,
241
- not this package's.
496
+ The handler applies bounded, protocol-level safeguards before or around Sources:
497
+
498
+ - a read batch may name at most `maxIdsPerEntity` distinct ids for one Entity
499
+ (default `1000`); oversized client batches fail rather than loading unbounded
500
+ rows;
501
+ - nested resolution is bounded by `maxDepth` (default `8`);
502
+ - the wire decoder also rejects a selection deeper than
503
+ `MAX_RELATION_DEPTH` (`8`) or more than `MAX_FIELDS_PER_REQUEST` (`256`)
504
+ fields for one Entity;
505
+ - returned field names are copied with `Object.hasOwn` into null-prototype
506
+ objects, so names such as `__proto__` or `toString` cannot reach prototypes;
507
+ - Source errors are remapped to protocol error types without echoing application
508
+ internals.
509
+
510
+ A `liveHub` applies the same id bound to a subscription. A hand-written live
511
+ Source is responsible for any additional bounds appropriate to its backend.
512
+
513
+ ## What it does not own
514
+
515
+ `foldkit-remote-server` intentionally does **not** own:
516
+
517
+ - HTTP/WebSocket transport or serialization;
518
+ - authentication protocol or session storage;
519
+ - a database connection;
520
+ - the client's normalized cache;
521
+ - client rendering or Surface activation;
522
+ - durable/offline client-authored state.
523
+
524
+ Those boundaries keep this package an interpreter of the Remote contract rather
525
+ than another application runtime.
242
526
 
243
527
  ## See also
244
528
 
245
- - [Server-derived state](https://github.com/doeixd/foldkit-plus/blob/main/docs/remote.md) — the mental model for
246
- both halves.
247
- - [`foldkit-remote`](https://github.com/doeixd/foldkit-plus/tree/main/packages/remote) — the client half this answers; [`foldkit-remote-drizzle`](https://github.com/doeixd/foldkit-plus/tree/main/packages/remote-drizzle)
248
- compiles its selections and queries to SQL.
249
- - [`examples/kitchen-sink`](https://github.com/doeixd/foldkit-plus/tree/main/examples/kitchen-sink) — the server packages with a live hub, an optimistic
250
- insert confirmed in place, and retention.
529
+ - [Server-derived state](../../docs/remote.md) — the client/server mental model
530
+ and ownership rules.
531
+ - [`foldkit-remote`](../remote) — requirements, normalized client Model,
532
+ subscriptions, mutations, live reads, and retention.
533
+ - [`foldkit-remote-drizzle`](../remote-drizzle) — compile Entity selections and
534
+ Query windows into Drizzle reads.
535
+ - [`examples/kitchen-sink`](../../examples/kitchen-sink) — Remote +
536
+ RemoteServer + Drizzle + `liveHub` in one executable trace.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Effect, Schema, Stream } from "effect";
2
- import { Boundary, ConnectionChangeSchema, ConnectionIdentity, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RemoteDescriptor, RemoteRpcClient } from "foldkit-remote";
3
- import { Requirement } from "foldkit-surface";
2
+ import { Boundary, ConnectionChangeSchema, ConnectionIdentity, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RemoteDescriptor, RemoteRpcClient, Requirement } from "foldkit-remote";
4
3
  //#region src/index.d.ts
5
4
  declare const RemoteServerError_base: Schema.Class<RemoteServerError, Schema.TaggedStruct<"RemoteServerError", {
6
5
  readonly message: Schema.String;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;qBAiCa,0BAA0B;iBAOtB;WACN;WACA,QAAQ,SAAS;;iBAGX,oBAAoB;WAC1B;WACA;;WAEA,UAAU,SAAS,eAAe;WAClC,WAAW;;iBAGL,aAAa,GAAG;WACtB;;WAEA,SAAS;WACT,OACP,SAAS,oBAAoB,OAC1B,OAAO,OAAO,cAAc,eAAe,mBAAmB;;WAE1D,aAAa,WAAW,GAAG;;;YAI1B,mBAAmB,OAAO,OAAO,YAAY;iBA8CxC,gBAAgB;WACtB,QAAQ;WACR,WAAW,cAAc;;WAEzB,cAAc,cAAc;;iBAGtB,eAAe,GAAG;WACxB;WACA,OAAO,OAAO;WACd,QAAQ,OAAO;WACf,MAAM;aAAoB;aAAyB,WAAW;QAAQ,OAAO;aAEzE;aACA,UAAU,cAAc;aACxB,aAAa,cAAc;KAEtC,mBACA;;iBAIa;WACN,OAAO;aACL;aACA;aACA;;WAEF,OAAO;WACP,KAAK;;iBAGC,YAAY,GAAG;WACrB;WACA,OAAO,OAAO;WACd,MAAM;aACJ;aACA,QAAQ;aACR,WAAW;QAChB,OAAO,OAAO,WAAW,mBAAmB;;iBAGnC,WAAW,GAAG;WACpB;WACA,YAAY;aACV,cAAc,cAAc;aAC5B;aACA,WAAW;QAChB,OAAO,OAAO,OAAO,OAAO,YAAY,aAAa,mBAAmB;;iBAG/D,iBAAiB,GAAG;WAC1B,UAAU,o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qB,eAAe,GAAG;aACvC,mBAAmB,YAAY,GAAG;aAClC,gBAAgB,WAAW,GAAG;QACrC,iBAAiB,GAAG;;;;;;EAYL,WAAA,QAAA,kBAAgB,QAAU;;;;;;;EAsBlC,WAAA,GAAG,GAAC,QACL,iBAAiB,GAAG,IAAE,WACnB,GAAC,UACH,eAAe,GAAG,OAC1B,gBAAgB"}
package/dist/index.mjs CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Effect, Queue, Schema, Stream } from "effect";
2
- import { REMOTE_PROTOCOL_VERSION, RemoteLiveError, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, connectionIdentity, entityKey, refsIn, stableStringify } from "foldkit-remote";
3
- import { Requirement } from "foldkit-surface";
2
+ import { REMOTE_PROTOCOL_VERSION, RemoteLiveError, RemoteMutationError, RemoteProtocolError, RemoteQueryError, RemoteReadError, Requirement, connectionIdentity, entityKey, refsIn, stableStringify } from "foldkit-remote";
4
3
  //#region src/index.ts
5
4
  /**
6
5
  * `foldkit-remote-server` — server-side Sources and handler compilation.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-remote-server` — server-side Sources and handler compilation.\n *\n * Owns entity/query Sources, **selection authorization**, normalization, and\n * turning them into Effect RPC handlers. It does not own HTTP, serialization, or\n * auth protocol; `principal` is resolved outside and passed in.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport {\n REMOTE_PROTOCOL_VERSION,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n connectionIdentity,\n entityKey,\n refsIn,\n stableStringify,\n type Boundary,\n type ConnectionChangeSchema,\n type ConnectionIdentity,\n type LiveChange,\n type MutationDescriptor,\n type NormalizedPatch,\n type QueryDescriptor,\n type QueryWindow,\n type RelationRequirement,\n type RemoteDescriptor,\n type RemoteRpcClient,\n} from 'foldkit-remote'\nimport { Requirement } from 'foldkit-surface'\n\nexport class RemoteServerError extends Schema.TaggedError<RemoteServerError>()(\n 'RemoteServerError',\n {\n message: Schema.String,\n },\n) {}\n\nexport interface EntityRecord {\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n}\n\nexport interface EntitySourceContext<P> {\n readonly ids: readonly string[]\n readonly fields: readonly string[]\n /** A pagination window per requested relation field. */\n readonly windows?: Readonly<Record<string, QueryWindow>> | undefined\n readonly principal: P\n}\n\nexport interface EntitySource<P, R = never> {\n readonly entity: string\n /** The fields the entity declares; a request for any other never reaches `read`. */\n readonly fields?: ReadonlySet<string> | undefined\n readonly read: (\n context: EntitySourceContext<P>,\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>\n /** Returns the fields this principal may read; omitted means all requested. */\n readonly authorize?: (principal: P, fields: readonly string[]) => readonly string[]\n}\n\n/** A connection change a mutation made, as the wire carries it. */\nexport type ConnectionChange = Schema.Schema.Type<typeof ConnectionChangeSchema>\n\nconst connectionChange = (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n position: 'prepend' | 'append' | 'remove',\n): ConnectionChange => {\n const edge = { entity: ref.entity, id: ref.id, key: entityKey(ref.entity, ref.id) }\n return position === 'remove'\n ? { _tag: 'Remove', connection: connectionIdentity(connection), edge }\n : { _tag: 'Insert', connection: connectionIdentity(connection), position, edge }\n}\n\n/**\n * The requested fields, in request order, that the source declares and the\n * principal may read. Never a field the client did not request, even if a\n * permissive `authorize` returns more.\n */\nconst allowedFields = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n requested: ReadonlyArray<string>,\n): ReadonlyArray<string> => {\n const declared =\n source.fields === undefined ? requested : requested.filter(field => source.fields!.has(field))\n if (declared.length === 0) return []\n const permitted = new Set(\n source.authorize === undefined ? declared : source.authorize(principal, declared),\n )\n return declared.filter(field => permitted.has(field))\n}\n\n/** The windows of the fields being read; only a field being read carries its window. */\nconst windowsOf = (\n windows: Readonly<Record<string, QueryWindow>> | undefined,\n fields: ReadonlyArray<string>,\n): { readonly windows?: Readonly<Record<string, QueryWindow>> } => {\n if (windows === undefined) return {}\n const kept = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(windows, field) ? [[field, windows[field]!] as const] : [],\n ),\n )\n return Object.keys(kept).length === 0 ? {} : { windows: kept }\n}\n\nexport interface MutationOutcome<Output> {\n readonly output: Output\n readonly entities?: ReadonlyArray<NormalizedPatch>\n /** Connection changes the mutation made; the client settles them with its patches. */\n readonly connections?: ReadonlyArray<ConnectionChange>\n}\n\nexport interface MutationSource<P, R = never> {\n readonly mutation: string\n readonly Input: Schema.Codec<unknown>\n readonly Output: Schema.Codec<unknown>\n readonly run: (context: { readonly input: unknown; readonly principal: P }) => Effect.Effect<\n {\n readonly output: unknown\n readonly entities: ReadonlyArray<NormalizedPatch>\n readonly connections: ReadonlyArray<ConnectionChange>\n },\n RemoteServerError,\n R\n >\n}\n\nexport interface QueryPage {\n readonly edges: ReadonlyArray<{\n readonly entity: string\n readonly id: string\n readonly key: string\n }>\n readonly start: Boundary\n readonly end: Boundary\n}\n\nexport interface QuerySource<P, R = never> {\n readonly query: string\n readonly Input: Schema.Codec<unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly window: QueryWindow\n readonly principal: P\n }) => Effect.Effect<QueryPage, RemoteServerError, R>\n}\n\nexport interface LiveSource<P, R = never> {\n readonly entity: string\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n }) => Stream.Stream<Schema.Schema.Type<typeof LiveChange>, RemoteServerError, R>\n}\n\nexport interface ServerDefinition<P, R = never> {\n readonly entities: ReadonlyMap<string, EntitySource<P, R>>\n readonly mutations: ReadonlyMap<string, MutationSource<P, R>>\n readonly queries: ReadonlyMap<string, QuerySource<P, R>>\n readonly live: ReadonlyMap<string, LiveSource<P, R>>\n}\n\n/** A read batch may not carry more than this many distinct ids per entity. */\nconst DEFAULT_MAX_IDS_PER_ENTITY = 1000\n\n/** A nested selection may not reach further than this many relation levels. */\nconst DEFAULT_MAX_DEPTH = 8\n\nexport interface HandlerOptions<P, R = never> {\n /** A read or live subscription may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many relation levels; default 8. */\n readonly maxDepth?: number | undefined\n /** A hub whose `changed`/`deleted` signals reach the subscribers this handler registers. */\n readonly live?: LiveHub<P, R> | undefined\n}\n\n/** Fails when the requirements name more distinct ids of one entity than `maxIds`. */\nconst checkIdsPerEntity = (\n requirements: ReadonlyArray<Requirement>,\n maxIds: number,\n): string | undefined => {\n const ids = new Map<string, Set<string>>()\n for (const requirement of requirements) {\n const seen = ids.get(requirement.entity) ?? new Set<string>()\n seen.add(requirement.id)\n ids.set(requirement.entity, seen)\n if (seen.size > maxIds) return requirement.entity\n }\n return undefined\n}\n\ntype LiveChangeValue = Schema.Schema.Type<typeof LiveChange>\ntype Uncursored<T> = T extends unknown ? Omit<T, 'cursor'> : never\n\ninterface LiveRef {\n readonly entity: string\n readonly id: string\n}\n\n/**\n * The server-side \"these fields changed\" signal. A hub tracks each live\n * subscriber's requirements (entity, id, fields) and principal; `changed`\n * re-reads the changed fields a subscriber selects through the entity's own\n * source, under that subscriber's principal, and streams the patch to it.\n * Subscribers that select none of the changed fields do no work. Cursors\n * continue from the cursor each subscriber resumed at, so the client's\n * duplicate and gap handling is unchanged.\n */\nexport interface LiveHub<P, R = never> {\n readonly changed: (\n ref: LiveRef,\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<void, RemoteServerError, R>\n readonly deleted: (ref: LiveRef) => Effect.Effect<void>\n /** Registers a subscriber for the stream's lifetime; `handlers` calls this. */\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n /** Refuses a subscription naming more ids of one entity than this. */\n readonly maxIdsPerEntity?: number | undefined\n }) => Stream.Stream<LiveChangeValue, RemoteServerError>\n /** How many subscribers are registered now. */\n readonly size: Effect.Effect<number>\n}\n\ninterface Selected {\n readonly fields: Set<string>\n /** The window each paged field was subscribed with, so a re-read pages the same way. */\n readonly windows: Map<string, QueryWindow>\n}\n\n/** The subscribers one source read answers, and the fields each wants of it. */\ninterface ReadGroup<P> {\n readonly windows: Readonly<Record<string, QueryWindow>>\n readonly entries: Array<{ readonly subscriber: Subscriber<P>; readonly fields: string[] }>\n}\n\ninterface Subscriber<P> {\n /** Per entity:id, the fields (and their windows) this subscriber selects. */\n readonly selected: ReadonlyMap<string, Selected>\n readonly principal: P\n readonly queue: Queue.Queue<LiveChangeValue>\n cursor: number\n}\n\nconst liveHub = <P, R>(entities: ReadonlyArray<EntitySource<P, R>>): Effect.Effect<LiveHub<P, R>> =>\n Effect.sync(() => {\n const sources = new Map(entities.map(source => [source.entity, source]))\n const subscribers = new Set<Subscriber<P>>()\n const emit = (subscriber: Subscriber<P>, change: Uncursored<LiveChangeValue>) => {\n subscriber.cursor += 1\n return Queue.offer(subscriber.queue, {\n ...change,\n cursor: subscriber.cursor,\n } as LiveChangeValue)\n }\n\n return {\n subscribe: ({ requirements, after, principal, maxIdsPerEntity }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const over = checkIdsPerEntity(\n requirements,\n Math.max(1, maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY),\n )\n if (over !== undefined) {\n return yield* new RemoteServerError({\n message: `Too many \"${over}\" ids in one live subscription`,\n })\n }\n const selected = new Map<string, Selected>()\n for (const requirement of requirements) {\n const key = `${requirement.entity}:${requirement.id}`\n const entry = selected.get(key) ?? { fields: new Set<string>(), windows: new Map() }\n for (const field of requirement.fields) entry.fields.add(field)\n for (const [field, window] of Object.entries(requirement.windows ?? {})) {\n entry.windows.set(field, window)\n }\n selected.set(key, entry)\n }\n const subscriber: Subscriber<P> = {\n selected,\n principal,\n queue: yield* Queue.unbounded<LiveChangeValue>(),\n cursor: after,\n }\n subscribers.add(subscriber)\n return Stream.fromQueue(subscriber.queue).pipe(\n Stream.ensuring(Effect.sync(() => void subscribers.delete(subscriber))),\n )\n }),\n ),\n\n changed: (ref, fields) =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n const source = sources.get(ref.entity)\n if (source === undefined) return\n // One source read per principal (by identity) and window signature:\n // subscribers sharing both share the read, and a paged field is\n // re-read with the window the subscriber selected it with.\n const groups = new Map<P, Map<string, ReadGroup<P>>>()\n for (const subscriber of subscribers) {\n const selected = subscriber.selected.get(key)\n if (selected === undefined) continue\n const wanted = fields.filter(field => selected.fields.has(field))\n if (wanted.length === 0) continue\n const windows = Object.fromEntries(\n wanted.flatMap(field => {\n const window = selected.windows.get(field)\n return window === undefined ? [] : [[field, window] as const]\n }),\n )\n const byWindows = groups.get(subscriber.principal) ?? new Map<string, ReadGroup<P>>()\n groups.set(subscriber.principal, byWindows)\n const windowKey = stableStringify(windows)\n const group = byWindows.get(windowKey) ?? { windows, entries: [] }\n byWindows.set(windowKey, group)\n group.entries.push({ subscriber, fields: wanted })\n }\n for (const [principal, byWindows] of groups) {\n for (const { windows, entries: group } of byWindows.values()) {\n const requested = [...new Set(group.flatMap(entry => entry.fields))]\n const allowed = allowedFields(source, principal, requested)\n if (allowed.length === 0) continue\n const allowedSet = new Set(allowed)\n const records = yield* source.read({\n ids: [ref.id],\n fields: allowed,\n principal,\n ...windowsOf(windows, allowed),\n })\n const record = records.find(candidate => candidate.id === ref.id)\n if (record === undefined) continue\n for (const { subscriber, fields: wanted } of group) {\n const values: Record<string, unknown> = Object.create(null)\n for (const field of wanted) {\n if (allowedSet.has(field) && Object.hasOwn(record.values, field)) {\n values[field] = record.values[field]\n }\n }\n const changed = Object.keys(values)\n if (changed.length === 0) continue\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values,\n changed,\n })\n }\n }\n }\n }),\n\n deleted: ref =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n for (const subscriber of subscribers) {\n if (!subscriber.selected.has(key)) continue\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n }\n }),\n\n size: Effect.sync(() => subscribers.size),\n }\n })\n\nconst protocolMismatch = (received: number): RemoteProtocolError | undefined =>\n received === REMOTE_PROTOCOL_VERSION\n ? undefined\n : new RemoteProtocolError({\n message: `Remote protocol version ${received} is not ${REMOTE_PROTOCOL_VERSION}`,\n expected: REMOTE_PROTOCOL_VERSION,\n received,\n })\n\ninterface EntityGroup {\n readonly ids: Set<string>\n /** The union of the requests' fields, windows, and relations. */\n slice: RelationRequirement\n}\n\n/**\n * One level's requests grouped per entity and window signature: ids and\n * slices unioned. Requests that page a relation differently are separate\n * groups, so one window never answers for another id.\n */\nconst groupByEntity = (requests: ReadonlyArray<Requirement>): EntityGroup[] => {\n const grouped = new Map<string, EntityGroup>()\n for (const request of requests) {\n const groupKey = `${request.entity}\\u0000${stableStringify(request.windows ?? null)}`\n const group = grouped.get(groupKey)\n if (group === undefined) {\n grouped.set(groupKey, {\n ids: new Set([request.id]),\n slice: Requirement.mergeRelation({ entity: request.entity, fields: [] }, request),\n })\n } else {\n group.ids.add(request.id)\n group.slice = Requirement.mergeRelation(group.slice, request)\n }\n }\n return [...grouped.values()]\n}\n\n/** A descriptor's name and, when it declares them, its fields. */\ninterface EntityName {\n readonly name: string\n readonly fields?: Readonly<Record<string, unknown>> | undefined\n}\n\nexport const RemoteServer = {\n /** A mutation outcome's report that `ref` now heads the connection. */\n prepend: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'prepend'),\n\n /** A mutation outcome's report that `ref` now ends the connection. */\n append: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'append'),\n\n /** A mutation outcome's report that `ref` left the connection. */\n remove: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'remove'),\n\n /**\n * An entity source. Given the Entity (or anything with its `name` and\n * `fields`), a request for a field the entity does not declare never\n * reaches `read` or `authorize`.\n */\n entity: <P = unknown, R = never>(\n entity: EntityName,\n options: {\n readonly read: EntitySource<P, R>['read']\n readonly authorize?: EntitySource<P, R>['authorize']\n },\n ): EntitySource<P, R> => ({\n entity: entity.name,\n ...(entity.fields === undefined ? {} : { fields: new Set(Object.keys(entity.fields)) }),\n read: options.read,\n ...(options.authorize === undefined ? {} : { authorize: options.authorize }),\n }),\n\n mutation: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n >(\n mutation: MutationDescriptor<Name, Input, Output>,\n run: (context: {\n readonly input: Input\n readonly principal: P\n }) => Effect.Effect<MutationOutcome<Output>, RemoteServerError, R>,\n ): MutationSource<P, R> => ({\n mutation: mutation.name,\n Input: mutation.Input,\n Output: mutation.Output,\n run: context =>\n run({ input: context.input as Input, principal: context.principal }).pipe(\n Effect.map(outcome => ({\n output: outcome.output,\n entities: outcome.entities ?? [],\n connections: outcome.connections ?? [],\n })),\n ),\n }),\n\n query: <P = unknown, R = never, Input = unknown>(\n query: QueryDescriptor<string, Input, unknown>,\n run: (context: {\n readonly input: Input\n readonly window: QueryWindow\n readonly principal: P\n }) => Effect.Effect<QueryPage, RemoteServerError, R>,\n ): QuerySource<P, R> => ({\n query: query.name,\n Input: query.Input,\n run: context =>\n run({ input: context.input as Input, window: context.window, principal: context.principal }),\n }),\n\n /** Streams live entity patches for a client's live requirements. */\n live: <P = unknown, R = never>(\n entity: EntityName,\n options: { readonly subscribe: LiveSource<P, R>['subscribe'] },\n ): LiveSource<P, R> => ({\n entity: entity.name,\n subscribe: options.subscribe,\n }),\n\n /**\n * A `LiveHub` over entity sources. Pass it to `handlers` as `live`, then\n * call `hub.changed(ref, fields)` from wherever the data changes (a mutation\n * source, a database trigger); each subscriber that selects any of those\n * fields receives them, re-read through the entity source under its own\n * principal. It needs only the entity sources, so the mutation sources that\n * signal it can be built after it.\n */\n liveHub,\n\n make: <P = unknown, R = never>(config: {\n readonly entities: readonly EntitySource<P, R>[]\n readonly mutations?: readonly MutationSource<P, R>[]\n readonly queries?: readonly QuerySource<P, R>[]\n readonly live?: readonly LiveSource<P, R>[]\n }): ServerDefinition<P, R> => ({\n entities: new Map(config.entities.map(source => [source.entity, source])),\n mutations: new Map((config.mutations ?? []).map(source => [source.mutation, source])),\n queries: new Map((config.queries ?? []).map(source => [source.query, source])),\n live: new Map((config.live ?? []).map(source => [source.entity, source])),\n }),\n\n /**\n * Checks every source name against the declared domain, so an undeclared\n * entity/query/mutation fails at startup rather than returning nothing at\n * call time.\n */\n validate: (domain: RemoteDescriptor, server: ServerDefinition<any, any>): void => {\n const assertDeclared = (\n kind: string,\n declared: ReadonlyMap<string, unknown>,\n names: Iterable<string>,\n ): void => {\n for (const name of names) {\n if (!declared.has(name))\n throw new Error(`RemoteServer: ${kind} \"${name}\" is not declared in the Remote domain`)\n }\n }\n assertDeclared('entity', domain.registry.entities, server.entities.keys())\n assertDeclared('query', domain.registry.queries, server.queries.keys())\n assertDeclared('mutation', domain.registry.mutations, server.mutations.keys())\n },\n\n /**\n * Compiles the server into the `Read`/`Mutate` RPC handlers. `principal` is\n * resolved outside (authentication middleware in a later phase); unknown\n * entities, entities with no allowed fields, and unknown mutations return an\n * error or nothing rather than leaking existence.\n */\n handlers: <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R> = {},\n ): RemoteRpcClient<R> => ({\n FoldkitRemoteRead: Effect.fn('RemoteServer.FoldkitRemoteRead')(function* (payload) {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return yield* mismatch\n\n const entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }> = []\n // What this batch has already read per entity:id (fields and values), so\n // a target several relations share is fetched once, a later spec's nested\n // relation is followed from the values already in hand, and a cyclic\n // selection stays finite.\n const fetched = new Map<string, Set<string>>()\n const fetchedValues = new Map<string, Record<string, unknown>>()\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH\n const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY)\n\n // The limit guards the client's batch, whatever windows split it into;\n // a nested level's fan-out is the server's own doing, so it is chunked\n // rather than refused.\n const over = checkIdsPerEntity(payload.requests, maxIds)\n if (over !== undefined) {\n return yield* new RemoteReadError({ message: `Too many \"${over}\" ids in one read batch` })\n }\n\n // Level by level: a level's relation refs become the next level's requests.\n let pending: ReadonlyArray<Requirement> = payload.requests\n for (let depth = 0; pending.length > 0; depth++) {\n if (depth > maxDepth) {\n return yield* new RemoteReadError({\n message: `Nested selection deeper than ${maxDepth} relation levels`,\n })\n }\n const next: Requirement[] = []\n\n /**\n * Follows each relation's refs in `values` into the next level, asking\n * only for fields this batch has not read of the target; a target read\n * in full already is followed further from its fetched values.\n */\n const follow = (\n values: Record<string, unknown>,\n relations: Readonly<Record<string, RelationRequirement>>,\n ): void => {\n for (const [field, relation] of Object.entries(relations)) {\n if (!Object.hasOwn(values, field)) continue\n for (const ref of refsIn(values[field])) {\n if (ref.entity !== relation.entity) continue\n const key = `${relation.entity}:${ref.id}`\n const read = fetched.get(key)\n const fields = relation.fields.filter(name => read?.has(name) !== true)\n if (fields.length > 0) {\n next.push({\n entity: relation.entity,\n id: ref.id,\n fields,\n ...(relation.windows === undefined ? {} : { windows: relation.windows }),\n ...(relation.relations === undefined ? {} : { relations: relation.relations }),\n })\n } else if (relation.relations !== undefined) {\n follow(fetchedValues.get(key) ?? {}, relation.relations)\n }\n }\n }\n }\n\n for (const { ids, slice } of groupByEntity(pending)) {\n const name = slice.entity\n const source = server.entities.get(name)\n if (source === undefined) continue\n const allowed = allowedFields(source, principal, slice.fields)\n if (allowed.length === 0) continue\n\n const windows = windowsOf(slice.windows, allowed)\n const idList = [...ids]\n const records: EntityRecord[] = []\n for (let start = 0; start < idList.length; start += maxIds) {\n records.push(\n ...(yield* source\n .read({\n ids: idList.slice(start, start + maxIds),\n fields: allowed,\n principal,\n ...windows,\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n )),\n )\n }\n\n for (const record of records) {\n // Null-prototype so a crafted field name (`__proto__`) cannot reach\n // the prototype, and `Object.hasOwn` so inherited names are ignored.\n const values: Record<string, unknown> = Object.create(null)\n for (const field of allowed) {\n if (Object.hasOwn(record.values, field)) values[field] = record.values[field]\n }\n entities.push({ entity: name, id: record.id, values })\n\n const key = `${name}:${record.id}`\n const known = fetched.get(key) ?? new Set<string>()\n for (const field of allowed) known.add(field)\n fetched.set(key, known)\n fetchedValues.set(key, { ...fetchedValues.get(key), ...values })\n\n // `values` holds only allowed fields, so a relation the principal\n // may not read is never followed.\n follow(values, slice.relations ?? {})\n }\n }\n // A target read by this level (as another group's request) is not\n // read again by the next.\n pending = next.flatMap(request => {\n const read = fetched.get(`${request.entity}:${request.id}`)\n const fields = request.fields.filter(field => read?.has(field) !== true)\n return fields.length === 0 ? [] : [{ ...request, fields }]\n })\n }\n\n return { entities }\n }),\n\n FoldkitRemoteMutate: Effect.fn('RemoteServer.FoldkitRemoteMutate')(function* (payload) {\n const source = server.mutations.get(payload.mutation)\n if (source === undefined) {\n return yield* new RemoteMutationError({\n message: `Unknown mutation: ${payload.mutation}`,\n })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation input' })),\n ),\n )\n\n const outcome = yield* source\n .run({ input, principal })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n )\n\n const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation output' })),\n ),\n )\n\n return {\n output,\n entities: outcome.entities.map(patch => ({\n entity: patch.entity,\n id: patch.id,\n values: patch.values,\n })),\n connections: outcome.connections,\n }\n }),\n\n FoldkitRemoteQuery: Effect.fn('RemoteServer.FoldkitRemoteQuery')(function* (payload) {\n const source = server.queries.get(payload.query)\n if (source === undefined) {\n return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteQueryError({ message: 'Invalid query input' })),\n ),\n )\n\n const page = yield* source\n .run({ input, window: payload.window, principal })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n\n return { edges: page.edges, start: page.start, end: page.end }\n }),\n\n FoldkitRemoteLive: payload => {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return Stream.fail(mismatch)\n const entities = [...new Set(payload.requirements.map(request => request.entity))]\n const streams: Array<Stream.Stream<LiveChangeValue, RemoteServerError, R>> = entities.flatMap(\n entity => {\n const source = server.live.get(entity)\n if (source === undefined) return []\n return [\n source.subscribe({\n requirements: payload.requirements.filter(request => request.entity === entity),\n after: payload.after,\n principal,\n }),\n ]\n },\n )\n if (options.live !== undefined) {\n streams.push(\n options.live.subscribe({\n requirements: payload.requirements,\n after: payload.after,\n principal,\n maxIdsPerEntity: options.maxIdsPerEntity,\n }),\n )\n }\n // An entity with no live source simply contributes nothing; the client's\n // planner refetches it rather than the stream failing.\n return Stream.mergeAll(streams, { concurrency: 'unbounded' }).pipe(\n Stream.mapError(error => new RemoteLiveError({ message: error.message })),\n )\n },\n }),\n}\n"],"mappings":";;;;;;;;;;;AAiCA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;AA6BH,MAAM,oBACJ,YACA,KACA,aACqB;CACrB,MAAM,OAAO;EAAE,QAAQ,IAAI;EAAQ,IAAI,IAAI;EAAI,KAAK,UAAU,IAAI,QAAQ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S,sBAAsB,CAAC,CAAC,CACtE,CACF;GAEA,MAAM,OAAO,OAAO,OACjB,IAAI;IAAE;IAAO,QAAQ,QAAQ;IAAQ;GAAU,CAAC,CAAC,CACjD,KACC,OAAO,SAAS,sBAAqB,UACnC,OAAO,KAAK,IAAI,iBAAiB,EAAE,SAAS,MAAM,QAAQ,CAAC,CAAC,CAC9D,CACF;GAEF,OAAO;IAAE,OAAO,KAAK;IAAO,OAAO,KAAK;IAAO,KAAK,KAAK;GAAI;EAC/D,CAAC;EAED,oBAAmB,YAAW;GAC5B,MAAM,WAAW,iBAAiB,QAAQ,OAAO;GACjD,IAAI,aAAa,KAAA,GAAW,OAAO,OAAO,KAAK,QAAQ;GAEvD,MAAM,UAAuE,CAD3D,GAAG,IAAI,IAAI,QAAQ,aAAa,KAAI,YAAW,QAAQ,MAAM,CAAC,CACI,CAAC,CAAC,SACpF,WAAU;IACR,MAAM,SAAS,OAAO,KAAK,IAAI,MAAM;IACrC,IAAI,WAAW,KAAA,GAAW,OAAO,CAAC;IAClC,OAAO,CACL,OAAO,UAAU;KACf,cAAc,QAAQ,aAAa,QAAO,YAAW,QAAQ,WAAW,MAAM;KAC9E,OAAO,QAAQ;KACf;IACF,CAAC,CACH;GACF,CACF;GACA,IAAI,QAAQ,SAAS,KAAA,GACnB,QAAQ,KACN,QAAQ,KAAK,UAAU;IACrB,cAAc,QAAQ;IACtB,OAAO,QAAQ;IACf;IACA,iBAAiB,QAAQ;GAC3B,CAAC,CACH;GAIF,OAAO,OAAO,SAAS,SAAS,EAAE,aAAa,YAAY,CAAC,CAAC,CAAC,KAC5D,OAAO,UAAS,UAAS,IAAI,gBAAgB,EAAE,SAAS,MAAM,QAAQ,CAAC,CAAC,CAC1E;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-remote-server` — server-side Sources and handler compilation.\n *\n * Owns entity/query Sources, **selection authorization**, normalization, and\n * turning them into Effect RPC handlers. It does not own HTTP, serialization, or\n * auth protocol; `principal` is resolved outside and passed in.\n */\nimport { Effect, Queue, Schema, Stream } from 'effect'\nimport {\n REMOTE_PROTOCOL_VERSION,\n RemoteLiveError,\n RemoteMutationError,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n connectionIdentity,\n entityKey,\n refsIn,\n stableStringify,\n type Boundary,\n type ConnectionChangeSchema,\n type ConnectionIdentity,\n type LiveChange,\n type MutationDescriptor,\n type NormalizedPatch,\n type QueryDescriptor,\n type QueryWindow,\n type RelationRequirement,\n type RemoteDescriptor,\n Requirement,\n type RemoteRpcClient,\n} from 'foldkit-remote'\n\nexport class RemoteServerError extends Schema.TaggedError<RemoteServerError>()(\n 'RemoteServerError',\n {\n message: Schema.String,\n },\n) {}\n\nexport interface EntityRecord {\n readonly id: string\n readonly values: Readonly<Record<string, unknown>>\n}\n\nexport interface EntitySourceContext<P> {\n readonly ids: readonly string[]\n readonly fields: readonly string[]\n /** A pagination window per requested relation field. */\n readonly windows?: Readonly<Record<string, QueryWindow>> | undefined\n readonly principal: P\n}\n\nexport interface EntitySource<P, R = never> {\n readonly entity: string\n /** The fields the entity declares; a request for any other never reaches `read`. */\n readonly fields?: ReadonlySet<string> | undefined\n readonly read: (\n context: EntitySourceContext<P>,\n ) => Effect.Effect<ReadonlyArray<EntityRecord>, RemoteServerError, R>\n /** Returns the fields this principal may read; omitted means all requested. */\n readonly authorize?: (principal: P, fields: readonly string[]) => readonly string[]\n}\n\n/** A connection change a mutation made, as the wire carries it. */\nexport type ConnectionChange = Schema.Schema.Type<typeof ConnectionChangeSchema>\n\nconst connectionChange = (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n position: 'prepend' | 'append' | 'remove',\n): ConnectionChange => {\n const edge = { entity: ref.entity, id: ref.id, key: entityKey(ref.entity, ref.id) }\n return position === 'remove'\n ? { _tag: 'Remove', connection: connectionIdentity(connection), edge }\n : { _tag: 'Insert', connection: connectionIdentity(connection), position, edge }\n}\n\n/**\n * The requested fields, in request order, that the source declares and the\n * principal may read. Never a field the client did not request, even if a\n * permissive `authorize` returns more.\n */\nconst allowedFields = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n requested: ReadonlyArray<string>,\n): ReadonlyArray<string> => {\n const declared =\n source.fields === undefined ? requested : requested.filter(field => source.fields!.has(field))\n if (declared.length === 0) return []\n const permitted = new Set(\n source.authorize === undefined ? declared : source.authorize(principal, declared),\n )\n return declared.filter(field => permitted.has(field))\n}\n\n/** The windows of the fields being read; only a field being read carries its window. */\nconst windowsOf = (\n windows: Readonly<Record<string, QueryWindow>> | undefined,\n fields: ReadonlyArray<string>,\n): { readonly windows?: Readonly<Record<string, QueryWindow>> } => {\n if (windows === undefined) return {}\n const kept = Object.fromEntries(\n fields.flatMap(field =>\n Object.hasOwn(windows, field) ? [[field, windows[field]!] as const] : [],\n ),\n )\n return Object.keys(kept).length === 0 ? {} : { windows: kept }\n}\n\nexport interface MutationOutcome<Output> {\n readonly output: Output\n readonly entities?: ReadonlyArray<NormalizedPatch>\n /** Connection changes the mutation made; the client settles them with its patches. */\n readonly connections?: ReadonlyArray<ConnectionChange>\n}\n\nexport interface MutationSource<P, R = never> {\n readonly mutation: string\n readonly Input: Schema.Codec<unknown>\n readonly Output: Schema.Codec<unknown>\n readonly run: (context: { readonly input: unknown; readonly principal: P }) => Effect.Effect<\n {\n readonly output: unknown\n readonly entities: ReadonlyArray<NormalizedPatch>\n readonly connections: ReadonlyArray<ConnectionChange>\n },\n RemoteServerError,\n R\n >\n}\n\nexport interface QueryPage {\n readonly edges: ReadonlyArray<{\n readonly entity: string\n readonly id: string\n readonly key: string\n }>\n readonly start: Boundary\n readonly end: Boundary\n}\n\nexport interface QuerySource<P, R = never> {\n readonly query: string\n readonly Input: Schema.Codec<unknown>\n readonly run: (context: {\n readonly input: unknown\n readonly window: QueryWindow\n readonly principal: P\n }) => Effect.Effect<QueryPage, RemoteServerError, R>\n}\n\nexport interface LiveSource<P, R = never> {\n readonly entity: string\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n }) => Stream.Stream<Schema.Schema.Type<typeof LiveChange>, RemoteServerError, R>\n}\n\nexport interface ServerDefinition<P, R = never> {\n readonly entities: ReadonlyMap<string, EntitySource<P, R>>\n readonly mutations: ReadonlyMap<string, MutationSource<P, R>>\n readonly queries: ReadonlyMap<string, QuerySource<P, R>>\n readonly live: ReadonlyMap<string, LiveSource<P, R>>\n}\n\n/** A read batch may not carry more than this many distinct ids per entity. */\nconst DEFAULT_MAX_IDS_PER_ENTITY = 1000\n\n/** A nested selection may not reach further than this many relation levels. */\nconst DEFAULT_MAX_DEPTH = 8\n\nexport interface HandlerOptions<P, R = never> {\n /** A read or live subscription may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many relation levels; default 8. */\n readonly maxDepth?: number | undefined\n /** A hub whose `changed`/`deleted` signals reach the subscribers this handler registers. */\n readonly live?: LiveHub<P, R> | undefined\n}\n\n/** Fails when the requirements name more distinct ids of one entity than `maxIds`. */\nconst checkIdsPerEntity = (\n requirements: ReadonlyArray<Requirement>,\n maxIds: number,\n): string | undefined => {\n const ids = new Map<string, Set<string>>()\n for (const requirement of requirements) {\n const seen = ids.get(requirement.entity) ?? new Set<string>()\n seen.add(requirement.id)\n ids.set(requirement.entity, seen)\n if (seen.size > maxIds) return requirement.entity\n }\n return undefined\n}\n\ntype LiveChangeValue = Schema.Schema.Type<typeof LiveChange>\ntype Uncursored<T> = T extends unknown ? Omit<T, 'cursor'> : never\n\ninterface LiveRef {\n readonly entity: string\n readonly id: string\n}\n\n/**\n * The server-side \"these fields changed\" signal. A hub tracks each live\n * subscriber's requirements (entity, id, fields) and principal; `changed`\n * re-reads the changed fields a subscriber selects through the entity's own\n * source, under that subscriber's principal, and streams the patch to it.\n * Subscribers that select none of the changed fields do no work. Cursors\n * continue from the cursor each subscriber resumed at, so the client's\n * duplicate and gap handling is unchanged.\n */\nexport interface LiveHub<P, R = never> {\n readonly changed: (\n ref: LiveRef,\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<void, RemoteServerError, R>\n readonly deleted: (ref: LiveRef) => Effect.Effect<void>\n /** Registers a subscriber for the stream's lifetime; `handlers` calls this. */\n readonly subscribe: (context: {\n readonly requirements: ReadonlyArray<Requirement>\n readonly after: number\n readonly principal: P\n /** Refuses a subscription naming more ids of one entity than this. */\n readonly maxIdsPerEntity?: number | undefined\n }) => Stream.Stream<LiveChangeValue, RemoteServerError>\n /** How many subscribers are registered now. */\n readonly size: Effect.Effect<number>\n}\n\ninterface Selected {\n readonly fields: Set<string>\n /** The window each paged field was subscribed with, so a re-read pages the same way. */\n readonly windows: Map<string, QueryWindow>\n}\n\n/** The subscribers one source read answers, and the fields each wants of it. */\ninterface ReadGroup<P> {\n readonly windows: Readonly<Record<string, QueryWindow>>\n readonly entries: Array<{ readonly subscriber: Subscriber<P>; readonly fields: string[] }>\n}\n\ninterface Subscriber<P> {\n /** Per entity:id, the fields (and their windows) this subscriber selects. */\n readonly selected: ReadonlyMap<string, Selected>\n readonly principal: P\n readonly queue: Queue.Queue<LiveChangeValue>\n cursor: number\n}\n\nconst liveHub = <P, R>(entities: ReadonlyArray<EntitySource<P, R>>): Effect.Effect<LiveHub<P, R>> =>\n Effect.sync(() => {\n const sources = new Map(entities.map(source => [source.entity, source]))\n const subscribers = new Set<Subscriber<P>>()\n const emit = (subscriber: Subscriber<P>, change: Uncursored<LiveChangeValue>) => {\n subscriber.cursor += 1\n return Queue.offer(subscriber.queue, {\n ...change,\n cursor: subscriber.cursor,\n } as LiveChangeValue)\n }\n\n return {\n subscribe: ({ requirements, after, principal, maxIdsPerEntity }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const over = checkIdsPerEntity(\n requirements,\n Math.max(1, maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY),\n )\n if (over !== undefined) {\n return yield* new RemoteServerError({\n message: `Too many \"${over}\" ids in one live subscription`,\n })\n }\n const selected = new Map<string, Selected>()\n for (const requirement of requirements) {\n const key = `${requirement.entity}:${requirement.id}`\n const entry = selected.get(key) ?? { fields: new Set<string>(), windows: new Map() }\n for (const field of requirement.fields) entry.fields.add(field)\n for (const [field, window] of Object.entries(requirement.windows ?? {})) {\n entry.windows.set(field, window)\n }\n selected.set(key, entry)\n }\n const subscriber: Subscriber<P> = {\n selected,\n principal,\n queue: yield* Queue.unbounded<LiveChangeValue>(),\n cursor: after,\n }\n subscribers.add(subscriber)\n return Stream.fromQueue(subscriber.queue).pipe(\n Stream.ensuring(Effect.sync(() => void subscribers.delete(subscriber))),\n )\n }),\n ),\n\n changed: (ref, fields) =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n const source = sources.get(ref.entity)\n if (source === undefined) return\n // One source read per principal (by identity) and window signature:\n // subscribers sharing both share the read, and a paged field is\n // re-read with the window the subscriber selected it with.\n const groups = new Map<P, Map<string, ReadGroup<P>>>()\n for (const subscriber of subscribers) {\n const selected = subscriber.selected.get(key)\n if (selected === undefined) continue\n const wanted = fields.filter(field => selected.fields.has(field))\n if (wanted.length === 0) continue\n const windows = Object.fromEntries(\n wanted.flatMap(field => {\n const window = selected.windows.get(field)\n return window === undefined ? [] : [[field, window] as const]\n }),\n )\n const byWindows = groups.get(subscriber.principal) ?? new Map<string, ReadGroup<P>>()\n groups.set(subscriber.principal, byWindows)\n const windowKey = stableStringify(windows)\n const group = byWindows.get(windowKey) ?? { windows, entries: [] }\n byWindows.set(windowKey, group)\n group.entries.push({ subscriber, fields: wanted })\n }\n for (const [principal, byWindows] of groups) {\n for (const { windows, entries: group } of byWindows.values()) {\n const requested = [...new Set(group.flatMap(entry => entry.fields))]\n const allowed = allowedFields(source, principal, requested)\n if (allowed.length === 0) continue\n const allowedSet = new Set(allowed)\n const records = yield* source.read({\n ids: [ref.id],\n fields: allowed,\n principal,\n ...windowsOf(windows, allowed),\n })\n const record = records.find(candidate => candidate.id === ref.id)\n if (record === undefined) continue\n for (const { subscriber, fields: wanted } of group) {\n const values: Record<string, unknown> = Object.create(null)\n for (const field of wanted) {\n if (allowedSet.has(field) && Object.hasOwn(record.values, field)) {\n values[field] = record.values[field]\n }\n }\n const changed = Object.keys(values)\n if (changed.length === 0) continue\n yield* emit(subscriber, {\n _tag: 'EntityPatched',\n entity: ref.entity,\n id: ref.id,\n values,\n changed,\n })\n }\n }\n }\n }),\n\n deleted: ref =>\n Effect.gen(function* () {\n const key = `${ref.entity}:${ref.id}`\n for (const subscriber of subscribers) {\n if (!subscriber.selected.has(key)) continue\n yield* emit(subscriber, { _tag: 'EntityDeleted', entity: ref.entity, id: ref.id })\n }\n }),\n\n size: Effect.sync(() => subscribers.size),\n }\n })\n\nconst protocolMismatch = (received: number): RemoteProtocolError | undefined =>\n received === REMOTE_PROTOCOL_VERSION\n ? undefined\n : new RemoteProtocolError({\n message: `Remote protocol version ${received} is not ${REMOTE_PROTOCOL_VERSION}`,\n expected: REMOTE_PROTOCOL_VERSION,\n received,\n })\n\ninterface EntityGroup {\n readonly ids: Set<string>\n /** The union of the requests' fields, windows, and relations. */\n slice: RelationRequirement\n}\n\n/**\n * One level's requests grouped per entity and window signature: ids and\n * slices unioned. Requests that page a relation differently are separate\n * groups, so one window never answers for another id.\n */\nconst groupByEntity = (requests: ReadonlyArray<Requirement>): EntityGroup[] => {\n const grouped = new Map<string, EntityGroup>()\n for (const request of requests) {\n const groupKey = `${request.entity}\\u0000${stableStringify(request.windows ?? null)}`\n const group = grouped.get(groupKey)\n if (group === undefined) {\n grouped.set(groupKey, {\n ids: new Set([request.id]),\n slice: Requirement.mergeRelation({ entity: request.entity, fields: [] }, request),\n })\n } else {\n group.ids.add(request.id)\n group.slice = Requirement.mergeRelation(group.slice, request)\n }\n }\n return [...grouped.values()]\n}\n\n/** A descriptor's name and, when it declares them, its fields. */\ninterface EntityName {\n readonly name: string\n readonly fields?: Readonly<Record<string, unknown>> | undefined\n}\n\nexport const RemoteServer = {\n /** A mutation outcome's report that `ref` now heads the connection. */\n prepend: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'prepend'),\n\n /** A mutation outcome's report that `ref` now ends the connection. */\n append: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'append'),\n\n /** A mutation outcome's report that `ref` left the connection. */\n remove: (\n connection: ConnectionIdentity,\n ref: { readonly entity: string; readonly id: string },\n ): ConnectionChange => connectionChange(connection, ref, 'remove'),\n\n /**\n * An entity source. Given the Entity (or anything with its `name` and\n * `fields`), a request for a field the entity does not declare never\n * reaches `read` or `authorize`.\n */\n entity: <P = unknown, R = never>(\n entity: EntityName,\n options: {\n readonly read: EntitySource<P, R>['read']\n readonly authorize?: EntitySource<P, R>['authorize']\n },\n ): EntitySource<P, R> => ({\n entity: entity.name,\n ...(entity.fields === undefined ? {} : { fields: new Set(Object.keys(entity.fields)) }),\n read: options.read,\n ...(options.authorize === undefined ? {} : { authorize: options.authorize }),\n }),\n\n mutation: <\n P = unknown,\n R = never,\n Name extends string = string,\n Input = unknown,\n Output = unknown,\n >(\n mutation: MutationDescriptor<Name, Input, Output>,\n run: (context: {\n readonly input: Input\n readonly principal: P\n }) => Effect.Effect<MutationOutcome<Output>, RemoteServerError, R>,\n ): MutationSource<P, R> => ({\n mutation: mutation.name,\n Input: mutation.Input,\n Output: mutation.Output,\n run: context =>\n run({ input: context.input as Input, principal: context.principal }).pipe(\n Effect.map(outcome => ({\n output: outcome.output,\n entities: outcome.entities ?? [],\n connections: outcome.connections ?? [],\n })),\n ),\n }),\n\n query: <P = unknown, R = never, Input = unknown>(\n query: QueryDescriptor<string, Input, unknown>,\n run: (context: {\n readonly input: Input\n readonly window: QueryWindow\n readonly principal: P\n }) => Effect.Effect<QueryPage, RemoteServerError, R>,\n ): QuerySource<P, R> => ({\n query: query.name,\n Input: query.Input,\n run: context =>\n run({ input: context.input as Input, window: context.window, principal: context.principal }),\n }),\n\n /** Streams live entity patches for a client's live requirements. */\n live: <P = unknown, R = never>(\n entity: EntityName,\n options: { readonly subscribe: LiveSource<P, R>['subscribe'] },\n ): LiveSource<P, R> => ({\n entity: entity.name,\n subscribe: options.subscribe,\n }),\n\n /**\n * A `LiveHub` over entity sources. Pass it to `handlers` as `live`, then\n * call `hub.changed(ref, fields)` from wherever the data changes (a mutation\n * source, a database trigger); each subscriber that selects any of those\n * fields receives them, re-read through the entity source under its own\n * principal. It needs only the entity sources, so the mutation sources that\n * signal it can be built after it.\n */\n liveHub,\n\n make: <P = unknown, R = never>(config: {\n readonly entities: readonly EntitySource<P, R>[]\n readonly mutations?: readonly MutationSource<P, R>[]\n readonly queries?: readonly QuerySource<P, R>[]\n readonly live?: readonly LiveSource<P, R>[]\n }): ServerDefinition<P, R> => ({\n entities: new Map(config.entities.map(source => [source.entity, source])),\n mutations: new Map((config.mutations ?? []).map(source => [source.mutation, source])),\n queries: new Map((config.queries ?? []).map(source => [source.query, source])),\n live: new Map((config.live ?? []).map(source => [source.entity, source])),\n }),\n\n /**\n * Checks every source name against the declared domain, so an undeclared\n * entity/query/mutation fails at startup rather than returning nothing at\n * call time.\n */\n validate: (domain: RemoteDescriptor, server: ServerDefinition<any, any>): void => {\n const assertDeclared = (\n kind: string,\n declared: ReadonlyMap<string, unknown>,\n names: Iterable<string>,\n ): void => {\n for (const name of names) {\n if (!declared.has(name))\n throw new Error(`RemoteServer: ${kind} \"${name}\" is not declared in the Remote domain`)\n }\n }\n assertDeclared('entity', domain.registry.entities, server.entities.keys())\n assertDeclared('query', domain.registry.queries, server.queries.keys())\n assertDeclared('mutation', domain.registry.mutations, server.mutations.keys())\n },\n\n /**\n * Compiles the server into the `Read`/`Mutate` RPC handlers. `principal` is\n * resolved outside (authentication middleware in a later phase); unknown\n * entities, entities with no allowed fields, and unknown mutations return an\n * error or nothing rather than leaking existence.\n */\n handlers: <P, R>(\n server: ServerDefinition<P, R>,\n principal: P,\n options: HandlerOptions<P, R> = {},\n ): RemoteRpcClient<R> => ({\n FoldkitRemoteRead: Effect.fn('RemoteServer.FoldkitRemoteRead')(function* (payload) {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return yield* mismatch\n\n const entities: Array<{\n readonly entity: string\n readonly id: string\n readonly values: Record<string, unknown>\n }> = []\n // What this batch has already read per entity:id (fields and values), so\n // a target several relations share is fetched once, a later spec's nested\n // relation is followed from the values already in hand, and a cyclic\n // selection stays finite.\n const fetched = new Map<string, Set<string>>()\n const fetchedValues = new Map<string, Record<string, unknown>>()\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH\n const maxIds = Math.max(1, options.maxIdsPerEntity ?? DEFAULT_MAX_IDS_PER_ENTITY)\n\n // The limit guards the client's batch, whatever windows split it into;\n // a nested level's fan-out is the server's own doing, so it is chunked\n // rather than refused.\n const over = checkIdsPerEntity(payload.requests, maxIds)\n if (over !== undefined) {\n return yield* new RemoteReadError({ message: `Too many \"${over}\" ids in one read batch` })\n }\n\n // Level by level: a level's relation refs become the next level's requests.\n let pending: ReadonlyArray<Requirement> = payload.requests\n for (let depth = 0; pending.length > 0; depth++) {\n if (depth > maxDepth) {\n return yield* new RemoteReadError({\n message: `Nested selection deeper than ${maxDepth} relation levels`,\n })\n }\n const next: Requirement[] = []\n\n /**\n * Follows each relation's refs in `values` into the next level, asking\n * only for fields this batch has not read of the target; a target read\n * in full already is followed further from its fetched values.\n */\n const follow = (\n values: Record<string, unknown>,\n relations: Readonly<Record<string, RelationRequirement>>,\n ): void => {\n for (const [field, relation] of Object.entries(relations)) {\n if (!Object.hasOwn(values, field)) continue\n for (const ref of refsIn(values[field])) {\n if (ref.entity !== relation.entity) continue\n const key = `${relation.entity}:${ref.id}`\n const read = fetched.get(key)\n const fields = relation.fields.filter(name => read?.has(name) !== true)\n if (fields.length > 0) {\n next.push({\n entity: relation.entity,\n id: ref.id,\n fields,\n ...(relation.windows === undefined ? {} : { windows: relation.windows }),\n ...(relation.relations === undefined ? {} : { relations: relation.relations }),\n })\n } else if (relation.relations !== undefined) {\n follow(fetchedValues.get(key) ?? {}, relation.relations)\n }\n }\n }\n }\n\n for (const { ids, slice } of groupByEntity(pending)) {\n const name = slice.entity\n const source = server.entities.get(name)\n if (source === undefined) continue\n const allowed = allowedFields(source, principal, slice.fields)\n if (allowed.length === 0) continue\n\n const windows = windowsOf(slice.windows, allowed)\n const idList = [...ids]\n const records: EntityRecord[] = []\n for (let start = 0; start < idList.length; start += maxIds) {\n records.push(\n ...(yield* source\n .read({\n ids: idList.slice(start, start + maxIds),\n fields: allowed,\n principal,\n ...windows,\n })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n )),\n )\n }\n\n for (const record of records) {\n // Null-prototype so a crafted field name (`__proto__`) cannot reach\n // the prototype, and `Object.hasOwn` so inherited names are ignored.\n const values: Record<string, unknown> = Object.create(null)\n for (const field of allowed) {\n if (Object.hasOwn(record.values, field)) values[field] = record.values[field]\n }\n entities.push({ entity: name, id: record.id, values })\n\n const key = `${name}:${record.id}`\n const known = fetched.get(key) ?? new Set<string>()\n for (const field of allowed) known.add(field)\n fetched.set(key, known)\n fetchedValues.set(key, { ...fetchedValues.get(key), ...values })\n\n // `values` holds only allowed fields, so a relation the principal\n // may not read is never followed.\n follow(values, slice.relations ?? {})\n }\n }\n // A target read by this level (as another group's request) is not\n // read again by the next.\n pending = next.flatMap(request => {\n const read = fetched.get(`${request.entity}:${request.id}`)\n const fields = request.fields.filter(field => read?.has(field) !== true)\n return fields.length === 0 ? [] : [{ ...request, fields }]\n })\n }\n\n return { entities }\n }),\n\n FoldkitRemoteMutate: Effect.fn('RemoteServer.FoldkitRemoteMutate')(function* (payload) {\n const source = server.mutations.get(payload.mutation)\n if (source === undefined) {\n return yield* new RemoteMutationError({\n message: `Unknown mutation: ${payload.mutation}`,\n })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation input' })),\n ),\n )\n\n const outcome = yield* source\n .run({ input, principal })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteMutationError({ message: error.message })),\n ),\n )\n\n const output = yield* Schema.encodeUnknownEffect(source.Output)(outcome.output).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteMutationError({ message: 'Invalid mutation output' })),\n ),\n )\n\n return {\n output,\n entities: outcome.entities.map(patch => ({\n entity: patch.entity,\n id: patch.id,\n values: patch.values,\n })),\n connections: outcome.connections,\n }\n }),\n\n FoldkitRemoteQuery: Effect.fn('RemoteServer.FoldkitRemoteQuery')(function* (payload) {\n const source = server.queries.get(payload.query)\n if (source === undefined) {\n return yield* new RemoteQueryError({ message: `Unknown query: ${payload.query}` })\n }\n\n const input = yield* Schema.decodeUnknownEffect(source.Input)(payload.input).pipe(\n Effect.catchTag('SchemaError', () =>\n Effect.fail(new RemoteQueryError({ message: 'Invalid query input' })),\n ),\n )\n\n const page = yield* source\n .run({ input, window: payload.window, principal })\n .pipe(\n Effect.catchTag('RemoteServerError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n\n return { edges: page.edges, start: page.start, end: page.end }\n }),\n\n FoldkitRemoteLive: payload => {\n const mismatch = protocolMismatch(payload.version)\n if (mismatch !== undefined) return Stream.fail(mismatch)\n const entities = [...new Set(payload.requirements.map(request => request.entity))]\n const streams: Array<Stream.Stream<LiveChangeValue, RemoteServerError, R>> = entities.flatMap(\n entity => {\n const source = server.live.get(entity)\n if (source === undefined) return []\n return [\n source.subscribe({\n requirements: payload.requirements.filter(request => request.entity === entity),\n after: payload.after,\n principal,\n }),\n ]\n },\n )\n if (options.live !== undefined) {\n streams.push(\n options.live.subscribe({\n requirements: payload.requirements,\n after: payload.after,\n principal,\n maxIdsPerEntity: options.maxIdsPerEntity,\n }),\n )\n }\n // An entity with no live source simply contributes nothing; the client's\n // planner refetches it rather than the stream failing.\n return Stream.mergeAll(streams, { concurrency: 'unbounded' }).pipe(\n Stream.mapError(error => new RemoteLiveError({ message: error.message })),\n )\n },\n }),\n}\n"],"mappings":";;;;;;;;;;AAiCA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,OAAO,OAClB,CACF,CAAC,CAAC,CAAC;AA6BH,MAAM,oBACJ,YACA,KACA,aACqB;CACrB,MAAM,OAAO;EAAE,QAAQ,IAAI;EAAQ,IAAI,IAAI;EAAI,KAAK,UAAU,IAAI,QAAQ,IAAI,EAAE;CAAE;CAClF,OAAO,aAAa,WAChB;EAAE,MAAM;EAAU,YAAY,mBAAmB,UAAU;EAAG;CAAK,IACnE;EAAE,MAAM;EAAU,YAAY,mBAAmB,UAAU;EAAG;EAAU;CAAK;AACnF;;;;;;AAOA,MAAM,iBACJ,QACA,WACA,cAC0B;CAC1B,MAAM,WACJ,OAAO,WAAW,KAAA,IAAY,YAAY,UAAU,QAAO,UAAS,OAAO,OAAQ,IAAI,KAAK,CAAC;CAC/F,IAAI,SAAS,WAAW,GAAG,OAAO,CAAC;CACnC,MAAM,YAAY,IAAI,IACpB,OAAO,cAAc,KAAA,IAAY,WAAW,OAAO,UAAU,WAAW,QAAQ,CAClF;CACA,OAAO,SAAS,QAAO,UAAS,UAAU,IAAI,KAAK,CAAC;AACtD;;AAGA,MAAM,aACJ,SACA,WACiE;CACjE,IAAI,YAAY,KAAA,GAAW,OAAO,CAAC;CACnC,MAAM,OAAO,OAAO,YAClB,OAAO,SAAQ,UACb,OAAO,OAAO,SAAS,KAAK,IAAI,CAAC,CAAC,OAAO,QAAQ,MAAO,CAAU,IAAI,CAAC,CACzE,CACF;CACA,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,CAAC,IAAI,EAAE,SAAS,KAAK;AAC/D;;AA6DA,MAAM,6BAA6B;;AAGnC,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AK,UAAU;IACrB,cAAc,QAAQ;IACtB,OAAO,QAAQ;IACf;IACA,iBAAiB,QAAQ;GAC3B,CAAC,CACH;GAIF,OAAO,OAAO,SAAS,SAAS,EAAE,aAAa,YAAY,CAAC,CAAC,CAAC,KAC5D,OAAO,UAAS,UAAS,IAAI,gBAAgB,EAAE,SAAS,MAAM,QAAQ,CAAC,CAAC,CAC1E;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-remote-server",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Server sources and handler compilation for foldkit-remote: entities, selection authorization, and normalization.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -38,8 +38,7 @@
38
38
  "LICENSE"
39
39
  ],
40
40
  "dependencies": {
41
- "foldkit-remote": "0.2.0",
42
- "foldkit-surface": "0.1.1"
41
+ "foldkit-remote": "0.3.0"
43
42
  },
44
43
  "peerDependencies": {
45
44
  "effect": "^4.0.0-rc.112"