foldkit-remote-server 0.21.0 → 0.23.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
@@ -296,6 +296,17 @@ A Query Source answers the ordered connection itself. The client's `select`
296
296
  travels with the request, and the handlers return the selected fields of the
297
297
  page's items with the edges, so one response carries both:
298
298
 
299
+ <!-- docs-check
300
+ import { type QueryWindow } from 'foldkit-remote'
301
+ import { type QueryPage, type RemoteServerError } from 'foldkit-remote-server'
302
+
303
+ declare const projectsPage: (args: {
304
+ readonly ownerId: string
305
+ readonly window: QueryWindow
306
+ readonly principal: unknown
307
+ }) => Effect.Effect<QueryPage, RemoteServerError>
308
+ -->
309
+
299
310
  ```ts
300
311
  import { Query } from 'foldkit-remote'
301
312
 
@@ -310,7 +321,7 @@ const ProjectsByOwnerSource = RemoteServer.query(
310
321
  ({ input, window, principal }) => projectsPage({ ownerId: input.ownerId, window, principal }),
311
322
  )
312
323
 
313
- const Server = RemoteServer.make({
324
+ const QueryServer = RemoteServer.make({
314
325
  entities: [ProjectSource],
315
326
  queries: [ProjectsByOwnerSource],
316
327
  })
@@ -351,6 +362,13 @@ A Mutation Source changes server-owned state. It returns the protocol output
351
362
  plus any normalized entity/connection changes that should settle the client's
352
363
  cache immediately:
353
364
 
365
+ <!-- docs-check
366
+ declare const renameProject: (
367
+ input: { readonly id: string; readonly name: string },
368
+ principal: unknown,
369
+ ) => Effect.Effect<{ readonly id: string }, RemoteServerError>
370
+ -->
371
+
354
372
  ```ts
355
373
  import { Effect } from 'effect'
356
374
  import { Mutation } from 'foldkit-remote'
@@ -396,6 +414,12 @@ refuse.
396
414
 
397
415
  A Source may additionally return connection changes:
398
416
 
417
+ <!-- docs-check
418
+ import { type ConnectionIdentity } from 'foldkit-remote'
419
+ declare const connection: ConnectionIdentity
420
+ declare const id: string
421
+ -->
422
+
399
423
  ```ts
400
424
  RemoteServer.prepend(connection, Project.ref(id))
401
425
  RemoteServer.append(connection, Project.ref(id))
@@ -441,6 +465,14 @@ A mutation declared as a `Write` (`Mutation.write`) needs no handler.
441
465
  keys the client named when it named some, and hands the row's id and new values
442
466
  to an `EntityWriter`, which writes them and answers the row as written:
443
467
 
468
+ <!-- docs-check
469
+ import { type EntityWriter } from 'foldkit-remote-server'
470
+
471
+ declare const EditProject: Parameters<typeof RemoteServer.write>[0]
472
+ declare const writer: (binding: unknown) => EntityWriter<unknown>
473
+ declare const Db: { readonly Project: unknown }
474
+ -->
475
+
444
476
  ```ts
445
477
  // `EditProject` is a Mutation.write; `writer` and the binding `Db` are foldkit-remote-drizzle's.
446
478
  RemoteServer.write(EditProject, writer(Db.Project))
@@ -557,7 +589,7 @@ left out of it, keeping what the patch gave.
557
589
  A Source whose write the server cannot see (a row of a join table, a count it
558
590
  keeps itself) names the row with no values, and the read answers all of it:
559
591
 
560
- ```ts
592
+ ```ts sketch
561
593
  // Sketch, inside a mutation Source over a `Post` Entity: a like in a join table
562
594
  // changes its post, so name the post and read nothing yourself.
563
595
  return { output: { liked: true }, entities: [Remote.patch(Post, input.postId, {})] }
@@ -614,6 +646,14 @@ There are three ways to produce one:
614
646
 
615
647
  ### Write a live Source directly
616
648
 
649
+ <!-- docs-check
650
+ import { type LiveSource } from 'foldkit-remote-server'
651
+
652
+ declare const projectEvents: (
653
+ context: Parameters<LiveSource<unknown>['subscribe']>[0],
654
+ ) => ReturnType<LiveSource<unknown>['subscribe']>
655
+ -->
656
+
617
657
  ```ts
618
658
  // `projectEvents` is your own stream of `LiveChange`s.
619
659
  const ProjectLive = RemoteServer.live(Project, {
@@ -683,17 +723,20 @@ fields it carries, each deletion as a deletion. A mutation Source names nothing
683
723
  twice.
684
724
 
685
725
  ```ts
686
- // Inside an Effect.gen: building a hub is an Effect.
687
- const entitySources = [ProjectSource]
688
- const hub = yield* RemoteServer.liveHub(entitySources)
726
+ // Building a hub is an Effect.
727
+ const program = Effect.gen(function* () {
728
+ const entitySources = [ProjectSource]
729
+ const hub = yield* RemoteServer.liveHub(entitySources)
689
730
 
690
- const handlers = RemoteServer.handlers(Server, principal, {
691
- live: hub,
692
- })
731
+ const handlers = RemoteServer.handlers(Server, principal, {
732
+ live: hub,
733
+ })
693
734
 
694
- // Only for a write that is not a mutation: a database trigger consumer, a job.
695
- yield* hub.changed(Project.ref('p1'), ['name'])
696
- yield* hub.deleted(Project.ref('p1'))
735
+ // Only for a write that is not a mutation: a database trigger consumer, a job.
736
+ yield* hub.changed(Project.ref('p1'), ['name'])
737
+ yield* hub.deleted(Project.ref('p1'))
738
+ return handlers
739
+ })
697
740
  ```
698
741
 
699
742
  A mutation's publish runs after its Source returned, so after a write that
@@ -727,8 +770,10 @@ the reader itself included when a Source answers a viewer-relative member (a
727
770
  fits Sources that answer only by role:
728
771
 
729
772
  ```ts
730
- const hub = yield* RemoteServer.liveHub(entitySources, {
731
- key: user => (user.isAdmin ? 'admin' : 'member'),
773
+ const keyed = Effect.gen(function* () {
774
+ return yield* RemoteServer.liveHub([ProjectSource], {
775
+ key: (user: Principal) => (user.isAdmin ? 'admin' : 'member'),
776
+ })
732
777
  })
733
778
  ```
734
779
 
@@ -798,12 +843,19 @@ The principal is a value, or a Context key that each call reads, so one
798
843
  handler set (one RPC layer) answers every request and authentication provides
799
844
  the key per request:
800
845
 
846
+ <!-- docs-check
847
+ declare const body: unknown
848
+ declare const user: Principal
849
+ -->
850
+
801
851
  ```ts
852
+ import { Context } from 'effect'
853
+
802
854
  class CurrentUser extends Context.Service<CurrentUser, Principal>()('app/CurrentUser') {}
803
- const handlers = RemoteServer.handlers(Server, CurrentUser)
855
+ const answering = RemoteServer.handlers(Server, CurrentUser)
804
856
 
805
857
  // per request, once authentication has resolved `user`
806
- RemoteServer.answer(handlers, body).pipe(Effect.provideService(CurrentUser, user))
858
+ RemoteServer.answer(answering, body).pipe(Effect.provideService(CurrentUser, user))
807
859
  ```
808
860
 
809
861
  Every handler then needs `CurrentUser`, which the types carry: a key holding
@@ -827,7 +879,7 @@ application-specific rather than field-selection policy.
827
879
  A complete server definition is just the collection of Sources:
828
880
 
829
881
  ```ts
830
- const Server = RemoteServer.make({
882
+ const FullServer = RemoteServer.make({
831
883
  entities: [ProjectSource],
832
884
  queries: [ProjectsByOwnerSource],
833
885
  mutations: [RenameProjectSource],
@@ -845,7 +897,7 @@ const Data = Remote.define({
845
897
  mutations: [RenameProject],
846
898
  })
847
899
 
848
- RemoteServer.validate(Data, Server)
900
+ RemoteServer.validate(Data, FullServer)
849
901
  ```
850
902
 
851
903
  That catches an Entity, Query, or Mutation Source whose name is not declared by
@@ -878,8 +930,14 @@ it refuses a write that names one, which it cannot check.
878
930
  Then compile it into handlers, once per principal, or once for every request
879
931
  with a Context key as the principal (see Authentication vs authorization):
880
932
 
933
+ <!-- docs-check
934
+ import { type LiveHub } from 'foldkit-remote-server'
935
+
936
+ declare const hub: LiveHub<Principal>
937
+ -->
938
+
881
939
  ```ts
882
- const handlers = RemoteServer.handlers(Server, principal, {
940
+ const bounded = RemoteServer.handlers(FullServer, principal, {
883
941
  maxIdsPerEntity: 1000,
884
942
  maxDepth: 8,
885
943
  live: hub,
@@ -995,7 +1053,7 @@ it over a real transport to try a client against HTTP, or to test another
995
1053
  server against it:
996
1054
 
997
1055
  ```ts
998
- const served = RemoteRpc.toLayer(RemoteServer.handlers(backend.server, undefined))
1056
+ const backendLayer = RemoteRpc.toLayer(RemoteServer.handlers(backend.server, undefined))
999
1057
  ```
1000
1058
 
1001
1059
  - Rows are in their **wire shape**: a relation is its ref key (`'User:u1'`),
@@ -1087,6 +1145,10 @@ queries, mutations and live streams cross it with their typed errors, and an
1087
1145
  interrupted call interrupts its handler. It returns once the client closes its
1088
1146
  end; interrupt it to stop sooner:
1089
1147
 
1148
+ <!-- docs-check
1149
+ declare const port: MessagePort
1150
+ -->
1151
+
1090
1152
  ```ts
1091
1153
  import { servePort } from 'foldkit-remote-server/port'
1092
1154
 
@@ -1159,9 +1221,9 @@ import { RpcSerialization, RpcServer } from 'effect/rpc'
1159
1221
  import { RemoteRpc } from 'foldkit-remote'
1160
1222
  import { RemoteServer, bodyLimit } from 'foldkit-remote-server'
1161
1223
 
1162
- // `server` is your RemoteServer.make; answered as an anonymous principal here.
1224
+ // `Server` is your RemoteServer.make; answered as a visitor here.
1163
1225
  const RpcRoutes = RpcServer.layer(RemoteRpc).pipe(
1164
- Layer.provide(RemoteRpc.toLayer(RemoteServer.handlers(server, 'anonymous'))),
1226
+ Layer.provide(RemoteRpc.toLayer(RemoteServer.handlers(Server, { isAdmin: false }))),
1165
1227
  Layer.provide(RpcServer.layerProtocolHttp({ path: '/rpc' })),
1166
1228
  Layer.provide(RpcSerialization.layerJson),
1167
1229
  Layer.provide(HttpRouter.middleware(bodyLimit(64 * 1024)).layer),
@@ -1175,6 +1237,12 @@ only over `Remote.rpcProtocolHttp(url)` in place of
1175
1237
  and loses its status: a durable write would then read as unreachable and be
1176
1238
  sent again for good.
1177
1239
 
1240
+ Decide who is asking from the HTTP request, in front of the route, never
1241
+ from the `headers` an `RpcMiddleware` or a handler is given. `RpcServer`
1242
+ puts the HTTP request's headers before those the request body carries and
1243
+ keeps the last of each name, so a body can claim another `cookie`, `origin`
1244
+ or CSRF header; over a WebSocket, every frame can.
1245
+
1178
1246
  ## Over fetch (Workers)
1179
1247
 
1180
1248
  `serveFetch` from `foldkit-remote-server/fetch` is that route as a value: a
@@ -1184,6 +1252,31 @@ Effect: `layer` is built from the environment, then `resolvePrincipal` says
1184
1252
  who is asking, then the request is answered as them. The resolver may need
1185
1253
  what `layer` provides (a session store, an auth service):
1186
1254
 
1255
+ <!-- docs-check standalone
1256
+ import { Context, Effect, Layer } from 'effect'
1257
+ import { RemoteServer } from 'foldkit-remote-server'
1258
+ import { type RemoteClient, type RemoteUnauthenticated } from 'foldkit-remote'
1259
+
1260
+ type Principal = { readonly isAdmin: boolean }
1261
+ interface Env {
1262
+ readonly DB: unknown
1263
+ }
1264
+ class Database extends Context.Service<Database, unknown>()('readme/Database') {}
1265
+ const server = RemoteServer.make<Principal, Database>({ entities: [] })
1266
+ const drizzle = (db: unknown) => db
1267
+ const databaseLayer = (db: unknown) => Layer.succeed(Database, db)
1268
+ const resolvePrincipal = (request: Request) =>
1269
+ Effect.succeed<Principal>({ isAdmin: request.headers.has('x-admin') })
1270
+ const resolvePage = () => Effect.succeed<Principal>({ isAdmin: false })
1271
+ const PageContext = {
1272
+ attach: (
1273
+ request: Request,
1274
+ _: { readonly reader: Layer.Layer<RemoteClient, RemoteUnauthenticated> },
1275
+ ) => request,
1276
+ }
1277
+ const pages = { fetch: (request: Request) => Promise.resolve(new Response(request.url)) }
1278
+ -->
1279
+
1187
1280
  ```ts
1188
1281
  import { serveFetch } from 'foldkit-remote-server/fetch'
1189
1282
 
@@ -1192,8 +1285,8 @@ export default {
1192
1285
  fetch: serveFetch({
1193
1286
  server,
1194
1287
  resolvePrincipal: request =>
1195
- Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),
1196
- layer: env => databaseLayer(drizzle(env.DB)),
1288
+ Effect.succeed({ isAdmin: request.headers.get('x-role') === 'admin' }),
1289
+ layer: (env: Env) => databaseLayer(drizzle(env.DB)),
1197
1290
  }),
1198
1291
  }
1199
1292
  ```
@@ -1262,6 +1355,31 @@ from the same config `serveFetch` takes: the request's `RemoteClient` as a
1262
1355
  Layer, answered by the server's own handlers with no HTTP in between. The
1263
1356
  server, its `layer` and its limits are the ones `/remote` answers with.
1264
1357
 
1358
+ <!-- docs-check standalone
1359
+ import { Context, Effect, Layer } from 'effect'
1360
+ import { RemoteServer } from 'foldkit-remote-server'
1361
+ import { type RemoteClient, type RemoteUnauthenticated } from 'foldkit-remote'
1362
+
1363
+ type Principal = { readonly isAdmin: boolean }
1364
+ interface Env {
1365
+ readonly DB: unknown
1366
+ }
1367
+ class Database extends Context.Service<Database, unknown>()('readme/Database') {}
1368
+ const server = RemoteServer.make<Principal, Database>({ entities: [] })
1369
+ const drizzle = (db: unknown) => db
1370
+ const databaseLayer = (db: unknown) => Layer.succeed(Database, db)
1371
+ const resolvePrincipal = (request: Request) =>
1372
+ Effect.succeed<Principal>({ isAdmin: request.headers.has('x-admin') })
1373
+ const resolvePage = () => Effect.succeed<Principal>({ isAdmin: false })
1374
+ const PageContext = {
1375
+ attach: (
1376
+ request: Request,
1377
+ _: { readonly reader: Layer.Layer<RemoteClient, RemoteUnauthenticated> },
1378
+ ) => request,
1379
+ }
1380
+ const pages = { fetch: (request: Request) => Promise.resolve(new Response(request.url)) }
1381
+ -->
1382
+
1265
1383
  ```ts
1266
1384
  import { pageReader, serveFetch } from 'foldkit-remote-server/fetch'
1267
1385
 
@@ -1283,8 +1401,11 @@ export default {
1283
1401
 
1284
1402
  The resolver is the page's own: a page `GET` is a navigation, which carries
1285
1403
  no header a script adds, so a resolver that asks for one (Yielded's CSRF
1286
- header) refuses it. With `foldkit-auth`, give
1287
- `AuthServer.resolver({ …, requests: 'navigation' })`. When the reader is
1404
+ header) refuses it. With `foldkit-auth`, give `AuthServer.host`'s
1405
+ `navigation`. `pageReader` hands its resolver a `NavigationRequest` and
1406
+ `serveFetch` a `ScriptedRequest` (types from `foldkit-remote`, nothing at run
1407
+ time): a resolver typed for one does not fit the other, while one taking any
1408
+ `Request`, as here, fits both. When the reader is
1288
1409
  provided, the principal is resolved and `layer` built, and `layer` closes
1289
1410
  when that Effect ends, so provide it to the pre-read itself
1290
1411
  (`Data.satisfy(…).pipe(Effect.provide(reader))`). A refusal fails it with
@@ -1296,8 +1417,10 @@ principal it resolves must never write, and a render keeps no stream.
1296
1417
 
1297
1418
  With `cache`, the reader answers each read it proves public as the visitor,
1298
1419
  and notes every read for the render (`PageReads`): public with its
1299
- freshness and the rows it holds, or private. `foldkit-ssr`'s `SSR.entry`
1300
- keeps a page only when every read it made was public.
1420
+ freshness and the rows it holds, or private, named by the rows or query it
1421
+ asked for (`Price a, Price b`, `query Search`). `foldkit-ssr`'s `SSR.entry`
1422
+ keeps a page only when every read it made was public, and refuses a
1423
+ prerendered page naming the first read that was not.
1301
1424
 
1302
1425
  ### Keeping public reads: `cache`
1303
1426
 
@@ -1383,6 +1506,19 @@ write purges what this isolate kept, and another isolate's or data centre's
1383
1506
  copy stays until its `maxAge`. Give `pageReader` the same config, and pages
1384
1507
  read through it are judged the same way (`foldkit-ssr`'s `cache`).
1385
1508
 
1509
+ `CacheStore.kv(env.CACHE)` keeps them in a Workers KV namespace: one copy for
1510
+ every isolate and data centre. KV's free plan allows 1,000 writes a day, so
1511
+ an answer is written only when it is asked for a second time; this isolate's
1512
+ memory counts the asking, since counting in KV would spend the write the
1513
+ count saves. What KV refuses or fails never fails a request: a failed read
1514
+ is a miss, a refused write (the day's writes spent, a key over 512 bytes)
1515
+ keeps nothing, and each is logged as a warning. KV keeps an entry a minute
1516
+ at least; the store serves it for its `maxAge` alone. Its purge, like the
1517
+ Workers store's, reaches what this isolate kept. Its `keep` option is for
1518
+ pages (`foldkit-ssr`): with it, `kv` returns a `PageCacheStore`, which
1519
+ `serveFetch`'s `cache.store` refuses as a type error, since a read's answer
1520
+ carries no age and one served past its `maxAge` would read as fresh.
1521
+
1386
1522
  The checker answers each public read as two principals. `cache.check`
1387
1523
  answers it as who asks too, and where the two differ reports
1388
1524
  `CachedReadDiffers` and gives the asker their own: a development mode.
@@ -1432,7 +1568,34 @@ report)` in the layer the handlers run in. `serveFetch` takes one with the
1432
1568
  request beside it, used for everything that request runs, a broken layer
1433
1569
  included:
1434
1570
 
1571
+ <!-- docs-check standalone
1572
+ import { Context, Effect, Layer } from 'effect'
1573
+ import { RemoteServer } from 'foldkit-remote-server'
1574
+ import { type RemoteClient, type RemoteUnauthenticated } from 'foldkit-remote'
1575
+
1576
+ type Principal = { readonly isAdmin: boolean }
1577
+ interface Env {
1578
+ readonly DB: unknown
1579
+ }
1580
+ class Database extends Context.Service<Database, unknown>()('readme/Database') {}
1581
+ const server = RemoteServer.make<Principal, Database>({ entities: [] })
1582
+ const drizzle = (db: unknown) => db
1583
+ const databaseLayer = (env: Env) => Layer.succeed(Database, env.DB)
1584
+ const resolvePrincipal = (request: Request) =>
1585
+ Effect.succeed<Principal>({ isAdmin: request.headers.has('x-admin') })
1586
+ const resolvePage = () => Effect.succeed<Principal>({ isAdmin: false })
1587
+ const PageContext = {
1588
+ attach: (
1589
+ request: Request,
1590
+ _: { readonly reader: Layer.Layer<RemoteClient, RemoteUnauthenticated> },
1591
+ ) => request,
1592
+ }
1593
+ const pages = { fetch: (request: Request) => Promise.resolve(new Response(request.url)) }
1594
+ -->
1595
+
1435
1596
  ```ts
1597
+ import { serveFetch } from 'foldkit-remote-server/fetch'
1598
+
1436
1599
  serveFetch({
1437
1600
  server,
1438
1601
  resolvePrincipal,
@@ -1453,6 +1616,7 @@ A descriptor declared with
1453
1616
  value (`body`), and `evaluate` runs a body directly:
1454
1617
 
1455
1618
  ```ts standalone
1619
+ import { Schema } from 'effect'
1456
1620
  import { Entity, Expr, Order, Query, evaluate } from 'foldkit-entity'
1457
1621
 
1458
1622
  const Post = Entity.define('Post', Schema.Struct({ id: Schema.String, slug: Schema.String }))
@@ -1504,7 +1668,16 @@ what it is a reference *to*: the conformance suite, exported so an interpreter
1504
1668
  written elsewhere can be held to the same semantics. Here `run` is your
1505
1669
  interpreter:
1506
1670
 
1671
+ <!-- docs-check
1672
+ declare const run: (
1673
+ body: (typeof cases)[number]['body'],
1674
+ input: (typeof cases)[number]['input'],
1675
+ held: typeof rows,
1676
+ ) => ReadonlyArray<{ readonly id: string }>
1677
+ -->
1678
+
1507
1679
  ```ts
1680
+ import { expect } from 'vitest'
1508
1681
  import { cases, rows } from 'foldkit-entity/conformance'
1509
1682
 
1510
1683
  for (const { what, body, input, expected } of cases) {
package/dist/fetch.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { M as ServerDefinition, u as LiveHub } from "./index-pMrHmWZt.mjs";
1
+ import { M as ServerDefinition, u as LiveHub } from "./index-lJvjBBDL.mjs";
2
2
  import { Duration, Effect, Layer } from "effect";
3
- import { CacheStore, Diagnostic, RemoteClient, RemoteUnauthenticated } from "foldkit-remote";
3
+ import { CacheStore, Diagnostic, NavigationRequest, RemoteClient, RemoteUnauthenticated, ScriptedRequest } from "foldkit-remote";
4
4
  /** What `serveFetch` needs of the host runtime, per request. */
5
5
  export interface FetchConfig<P, R, Env, RP = never> {
6
6
  /** The server definition, as `RemoteServer.make` built it. */
@@ -9,8 +9,10 @@ export interface FetchConfig<P, R, Env, RP = never> {
9
9
  * Who this request is, from the request and the environment. Fails with
10
10
  * `RemoteServer.unauthenticated(reason?)` to refuse the caller: a 401.
11
11
  * What it needs (a session store, an auth service) comes from `layer`.
12
+ * A resolver taking any `Request` fits; one typed for a navigation
13
+ * (`NavigationRequest`) does not, since `/remote` writes.
12
14
  */
13
- readonly resolvePrincipal: (request: Request, env: Env) => Effect.Effect<P, RemoteUnauthenticated, RP>;
15
+ readonly resolvePrincipal: (request: ScriptedRequest, env: Env) => Effect.Effect<P, RemoteUnauthenticated, RP>;
14
16
  /**
15
17
  * What the Sources and the resolver need, from the environment. Built per
16
18
  * request, so kept cheap, and closed when the answer is sent, or, for a
@@ -76,6 +78,10 @@ export interface FetchConfig<P, R, Env, RP = never> {
76
78
  * says `private, no-store`. A write answered here purges the kept reads
77
79
  * holding a row it names, and every list of that row's entity.
78
80
  *
81
+ * `store` is a `CacheStore`, which serves nothing past its `maxAge`: an
82
+ * answer carries no age, so one kept longer would read as fresh. A
83
+ * `PageCacheStore` (`CacheStore.kv` with `keep`) is refused.
84
+ *
79
85
  * `visitor` is the principal of someone not signed in: refused when the
80
86
  * server's `viewer` names a row for it. With `check`, for development and
81
87
  * tests, each public read is also answered as who asks, and a difference
@@ -129,7 +135,15 @@ export declare const checkCache: <P, R, Env, RP = never>(config: Omit<FetchConfi
129
135
  * What `pageReader` reads of a `serveFetch` config: the server, its Sources'
130
136
  * layer, its limits, and the cache's `visitor`.
131
137
  */
132
- export type PageReaderConfig<P, R, Env, RP = never> = Pick<FetchConfig<P, R, Env, RP>, 'server' | 'resolvePrincipal' | 'layer' | 'maxIdsPerEntity' | 'maxDepth' | 'cache'>;
138
+ export type PageReaderConfig<P, R, Env, RP = never> = Pick<FetchConfig<P, R, Env, RP>, 'server' | 'layer' | 'maxIdsPerEntity' | 'maxDepth' | 'cache'> & {
139
+ /**
140
+ * Who a page request is. A resolver taking any `Request` fits; one typed
141
+ * for a script's request (`ScriptedRequest`) does not, since a navigation
142
+ * carries no header a script adds and that resolver would refuse every
143
+ * signed-in reader.
144
+ */
145
+ readonly resolvePrincipal: (request: NavigationRequest, env: Env) => Effect.Effect<P, RemoteUnauthenticated, RP>;
146
+ };
133
147
  /**
134
148
  * The reader a page render reads through, in the same process: the request's
135
149
  * `RemoteClient`, answered by the server's own handlers with no HTTP between
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBAgEiB,YAAY,GAAG,GAAG,KAAK;;WAE7B,QAAQ,iBAAiB,GAAG;;;;;;WAM5B,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;WAMpC,QAAQ,KAAK,QAAQ,MAAM,MAAM,IAAI;;WAErC;;;;;;;WAOA,YAAY,WAAW,MAAM,SAAS;;WAEtC,OAAO,QAAQ,GAAG;;;;;;;;;;;;WAYlB;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,gBAAgB,SAAS;;;;;;;;WAQzB,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;WAGjD;;WAEA;;;;;;;;WAQA;;;;;;;;;;;;;;;;;WAiBA;aAEM,OAAO;aACP,SAAS;aACT;;;;;;;;;;;;;;;;;;;;;;;;;;qBAgOJ,aAAc,GAAG,GAAG,KAAK,YAAU,QACtC,YAAY,GAAG,GAAG,KAAK,UAC5B,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;;;qBA2M/B,aAAoB,GAAG,GAAG,KAAK,YAAU,QAC5C,KAAK,YAAY,GAAG,GAAG,KAAK;WACzB;aAAkB,SAAS;;GACrC,UACS,oBAAoB,UAAQ,KACjC,QACJ;;;;;YAyBS,iBAAiB,GAAG,GAAG,KAAK,cAAc,KACpD,YAAY,GAAG,GAAG,KAAK;;;;;;;;;;;;;;;;;;;;qBAuBZ,aAAc,GAAG,GAAG,KAAK,YAAU,QAAU,iBAAiB,GAAG,GAAG,KAAK,SAAG,SAMtE,SAAO,KAAO,QAAM,MAAM,MAAM,cAAc"}
1
+ {"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBAkEiB,YAAY,GAAG,GAAG,KAAK;;WAE7B,QAAQ,iBAAiB,GAAG;;;;;;;;WAQ5B,mBACP,SAAS,iBACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;WAMpC,QAAQ,KAAK,QAAQ,MAAM,MAAM,IAAI;;WAErC;;;;;;;WAOA,YAAY,WAAW,MAAM,SAAS;;WAEtC,OAAO,QAAQ,GAAG;;;;;;;;;;;;WAYlB;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,gBAAgB,SAAS;;;;;;;;WAQzB,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;WAGjD;;WAEA;;;;;;;;WAQA;;;;;;;;;;;;;;;;;;;;;WAqBA;aAEM,OAAO;aACP,SAAS;aACT;;;;;;;;;;;;;;;;;;;;;;;;;;qBAgOJ,aAAc,GAAG,GAAG,KAAK,YAAU,QACtC,YAAY,GAAG,GAAG,KAAK,UAC5B,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;;;qBAiN/B,aAAoB,GAAG,GAAG,KAAK,YAAU,QAC5C,KAAK,YAAY,GAAG,GAAG,KAAK;WACzB;aAAkB,SAAS;;GACrC,UACS,oBAAoB,UAAQ,KACjC,QACJ;;;;;YAyBS,iBAAiB,GAAG,GAAG,KAAK,cAAc,KACpD,YAAY,GAAG,GAAG,KAAK;;;;;;;WASd,mBACP,SAAS,mBACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;;;;;;;;;;;;;;;;qBAsBlC,aAAc,GAAG,GAAG,KAAK,YAAU,QAAU,iBAAiB,GAAG,GAAG,KAAK,SAAG,SAWtE,SAAO,KAAO,QAAM,MAAM,MAAM,cAAc"}
package/dist/fetch.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { b as serverDefect, d as declaresTooLarge, f as readJson, i as RemoteServer, p as tooLargeAnswer, v as unauthenticatedAnswer, y as cachedReadDiffers } from "./src-CHkHaItI.mjs";
1
+ import { b as cachedReadDiffers, d as declaresTooLarge, f as discardBody, i as RemoteServer, m as tooLargeAnswer, p as readJson, x as serverDefect, y as unauthenticatedAnswer } from "./src-B1JAs_gH.mjs";
2
2
  import { Cause, Deferred, Duration, Effect, Exit, Layer, Option, Result, Schedule, Schema, Scope, Stream } from "effect";
3
3
  import { CacheStore, CachedRead, DEFAULT_MAX_BODY_BYTES, Diagnostics, LiveRequirement, MutationResult, PageReads, QueryRequest, QueryResult, ReadBatch, ReadBatchResult, Remote, RemoteJsonRequest, RemoteLiveError, RemoteMutationError, listTag, maxAgeSeconds, rowTag, shorterPolicy, stableStringify } from "foldkit-remote";
4
4
  // src/edgeCache.ts
@@ -75,6 +75,14 @@ const hex = (bytes) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16
75
75
  * Cache API keys by URL.
76
76
  */
77
77
  const cacheKey = (url, kind, text) => Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(Effect.map((digest) => `${new URL(url).origin}/__foldkit/cache/${kind}/${hex(digest)}`));
78
+ /** The most rows a private read names: a batch can ask for hundreds. */
79
+ const NAMED_ROWS = 3;
80
+ /** What a read batch asked for, as a refusal names it: its first rows, and how many more. */
81
+ const batchName = (batch) => {
82
+ const rows = batch.requests.map((request) => `${request.entity} ${request.id}`);
83
+ const more = rows.length - NAMED_ROWS;
84
+ return `${rows.slice(0, NAMED_ROWS).join(", ")}${more > 0 ? ` and ${more} more` : ""}`;
85
+ };
78
86
  /**
79
87
  * Handlers that answer every read and query proved public as `visitor`, and
80
88
  * note each read in the render's `PageReads`: public with its policy and
@@ -85,26 +93,32 @@ const notingHandlers = (server, own, visitor) => {
85
93
  const note = (read) => Effect.flatMap(Effect.service(PageReads), (noted) => Effect.sync(() => Option.map(noted, (add) => add(read))));
86
94
  return {
87
95
  ...own,
88
- FoldkitRemoteRead: (batch) => Option.match(Option.flatMap(visitor, (handlers) => Option.map(readPolicy(server, batch), (policy) => ({
89
- handlers,
90
- policy
91
- }))), {
92
- onNone: () => Effect.ensuring(own.FoldkitRemoteRead(batch), note(CachedRead.Private())),
93
- onSome: ({ handlers, policy }) => Effect.flatMap(handlers.FoldkitRemoteRead(batch), (result) => Effect.as(note(CachedRead.Public({
94
- policy,
95
- tags: readTags(batch, result)
96
- })), unaddressed(result))).pipe(Effect.onError(() => note(CachedRead.Private())))
97
- }),
98
- FoldkitRemoteQuery: (request) => Option.match(Option.flatMap(visitor, (handlers) => Option.map(queryPolicy(server, request), (policy) => ({
99
- handlers,
100
- policy
101
- }))), {
102
- onNone: () => Effect.ensuring(own.FoldkitRemoteQuery(request), note(CachedRead.Private())),
103
- onSome: ({ handlers, policy }) => Effect.flatMap(handlers.FoldkitRemoteQuery(request), (result) => Effect.as(note(CachedRead.Public({
104
- policy,
105
- tags: queryTags(server, request, result)
106
- })), unaddressed(result))).pipe(Effect.onError(() => note(CachedRead.Private())))
107
- })
96
+ FoldkitRemoteRead: (batch) => {
97
+ const unshared = note(CachedRead.Private({ read: batchName(batch) }));
98
+ return Option.match(Option.flatMap(visitor, (handlers) => Option.map(readPolicy(server, batch), (policy) => ({
99
+ handlers,
100
+ policy
101
+ }))), {
102
+ onNone: () => Effect.ensuring(own.FoldkitRemoteRead(batch), unshared),
103
+ onSome: ({ handlers, policy }) => Effect.flatMap(handlers.FoldkitRemoteRead(batch), (result) => Effect.as(note(CachedRead.Public({
104
+ policy,
105
+ tags: readTags(batch, result)
106
+ })), unaddressed(result))).pipe(Effect.onError(() => unshared))
107
+ });
108
+ },
109
+ FoldkitRemoteQuery: (request) => {
110
+ const unshared = note(CachedRead.Private({ read: `query ${request.query}` }));
111
+ return Option.match(Option.flatMap(visitor, (handlers) => Option.map(queryPolicy(server, request), (policy) => ({
112
+ handlers,
113
+ policy
114
+ }))), {
115
+ onNone: () => Effect.ensuring(own.FoldkitRemoteQuery(request), unshared),
116
+ onSome: ({ handlers, policy }) => Effect.flatMap(handlers.FoldkitRemoteQuery(request), (result) => Effect.as(note(CachedRead.Public({
117
+ policy,
118
+ tags: queryTags(server, request, result)
119
+ })), unaddressed(result))).pipe(Effect.onError(() => unshared))
120
+ });
121
+ }
108
122
  };
109
123
  };
110
124
  // src/fetch.ts
@@ -248,6 +262,7 @@ const serveFetch = (config) => {
248
262
  const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
249
263
  const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT;
250
264
  if (config.revalidate !== void 0 && !Duration.isGreaterThan(Duration.fromInputUnsafe(config.revalidate.every), Duration.zero)) throw new Error("serveFetch: revalidate.every must be longer than zero");
265
+ const resolvePrincipal = config.resolvePrincipal;
251
266
  /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */
252
267
  const reportingFor = (request) => (effect) => {
253
268
  const { diagnostics } = config;
@@ -257,7 +272,7 @@ const serveFetch = (config) => {
257
272
  const revalidation = (request, env, opened) => {
258
273
  const { revalidate } = config;
259
274
  if (revalidate === void 0) return Stream.empty;
260
- return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(Stream.mapEffect(() => config.resolvePrincipal(request, env)), Stream.mapEffect((now) => revalidate.key === void 0 || revalidate.key(opened) === revalidate.key(now) ? Effect.void : Effect.fail(new RemoteLiveError({ message: "Who is asking changed: open the stream again" }))), Stream.drain);
275
+ return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(Stream.mapEffect(() => resolvePrincipal(request, env)), Stream.mapEffect((now) => revalidate.key === void 0 || revalidate.key(opened) === revalidate.key(now) ? Effect.void : Effect.fail(new RemoteLiveError({ message: "Who is asking changed: open the stream again" }))), Stream.drain);
261
276
  };
262
277
  /**
263
278
  * A public read: the visitor's answer, from the store or answered and kept.
@@ -303,7 +318,7 @@ const serveFetch = (config) => {
303
318
  });
304
319
  /** `live` is whether the response streams, and so owns `scope` until it ends. */
305
320
  const respond = (request, env, scope) => Effect.gen(function* () {
306
- const principal = yield* config.resolvePrincipal(request, env);
321
+ const principal = yield* resolvePrincipal(request, env);
307
322
  const headers = config.headers?.(principal) ?? {};
308
323
  const body = yield* Effect.result(readJson(request, maxBodyBytes));
309
324
  if (Result.isFailure(body)) {
@@ -363,6 +378,7 @@ const serveFetch = (config) => {
363
378
  };
364
379
  return async (request, env) => {
365
380
  const response = await served(request, env);
381
+ await discardBody(request, maxBodyBytes);
366
382
  if (!response.headers.has("cache-control")) response.headers.set("cache-control", "private, no-store");
367
383
  return response;
368
384
  };
@@ -420,7 +436,8 @@ const pageReader = (config) => {
420
436
  maxDepth: config.maxDepth
421
437
  };
422
438
  const visitor = Option.map(Option.fromUndefinedOr(config.cache), (cache) => RemoteServer.handlers(config.server, cache.visitor, limits));
423
- return (request, env) => Layer.unwrap(Effect.map(config.resolvePrincipal(request, env), (principal) => {
439
+ const resolvePrincipal = config.resolvePrincipal;
440
+ return (request, env) => Layer.unwrap(Effect.map(resolvePrincipal(request, env), (principal) => {
424
441
  const handlers = notingHandlers(config.server, RemoteServer.handlers(config.server, principal, limits), visitor);
425
442
  return Remote.clientLayer({
426
443
  ...handlers,