foldkit-sync 0.9.0 → 0.10.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
@@ -262,10 +262,19 @@ an optional peer of this package):
262
262
  document, that `authorize` or `validate` refuses, or that reuses an id for
263
263
  other content fails the same way on every retry, so the replica drops it
264
264
  and the edits behind it still go. Only an entry with no id, a cursor ahead
265
- of the journal's, or the journal failing fails the exchange.
266
- - **`refuse(operation)`** rejects before the journal reads it, by what the
267
- transport established (a principal that may only read); a rule about the
268
- document belongs in `authorize`.
265
+ of the journal's, a connection `opens` refuses, or `admit` or the journal
266
+ failing fails the exchange.
267
+ - **`admit(operation)`** decides before the journal reads it, by what the
268
+ transport established (a principal that may only read) or by what cannot
269
+ run under the journal's lock (a rule that reads the rows an edit names,
270
+ `foldkit-guard/sync`): `true` admits, a refusal is rejected by id with its
271
+ reason, and it may answer with an `Effect`. A rule about the document
272
+ belongs in `authorize`.
273
+ - **`opens`**, an `Effect` of whether the connection may open the document at
274
+ all: refused, every exchange fails and nothing is read or appended, and
275
+ `serveJournal` sends it no notice of a commit. It is asked each exchange, so
276
+ access taken away holds from the next one.
277
+ `defineDocumentHost` takes both as functions of the principal.
269
278
  - **`settle`** runs after each exchange's appends: apply what committed to
270
279
  another store, through `journal.recover`. It runs every exchange, so a
271
280
  write that failed is tried again.
@@ -279,6 +288,57 @@ the exchange by hand, with an effect policy per committed operation.
279
288
 
280
289
  A server that is not Durable implements the same [exchange](#the-exchange).
281
290
 
291
+ ## Serving from a Durable Object
292
+
293
+ On Cloudflare, one object per document is the single writer the journal
294
+ wants. `defineDocumentHost` from `foldkit-sync/do` defines that class: each
295
+ accepted socket exchanges against the same journal through `serveJournal`,
296
+ and the replica side is the socket transport it already speaks:
297
+
298
+ ```ts
299
+ import { DurableObject } from 'cloudflare:workers'
300
+ import { defineDocumentHost } from 'foldkit-sync/do'
301
+
302
+ export class SyncHost extends defineDocumentHost(DurableObject, {
303
+ sync: TodoSync,
304
+ // A D1 journal as the durable D1 guide opens one.
305
+ openJournal: (_ctx, env) => openTodosJournal(env.DB),
306
+ resolvePrincipal: request => request.headers.get('x-actor') ?? 'anon',
307
+ }) {}
308
+ ```
309
+
310
+ ```ts
311
+ // The worker: one object per document.
312
+ export default {
313
+ fetch: (request: Request, env: Env): Promise<Response> =>
314
+ env.SYNC_HOST.get(env.SYNC_HOST.idFromName('todos')).fetch(request),
315
+ }
316
+ ```
317
+
318
+ ```ts
319
+ // A replica: the reconnecting client it already speaks.
320
+ Sync.transport.socket({ url: 'wss://example.com/sync' })
321
+ ```
322
+
323
+ - The base class is a parameter, so the module imports no worker runtime.
324
+ `openJournal` runs once, on the first upgrade: over D1 (`d1: true`, see
325
+ [the durable D1 guide](../durable/README.md#on-cloudflare-d1-d1-true)), or
326
+ the object's SQLite storage through `ctx`.
327
+ - Each upgrade resolves its own principal; non-upgrades are 404s that open
328
+ nothing. A journal that never opened is a 500 that says nothing of it.
329
+ - `settle: (env, journal) => Effect` runs after each exchange's appends, before
330
+ the reply is read, to apply what committed elsewhere — the Remote tables a
331
+ reader then queries. `journal.recover` makes it crash-safe and idempotent;
332
+ `env` and the journal are handed over because the store they reach lives
333
+ outside the exchange.
334
+ - A server socket is not a live stream: another request cannot wake the fiber
335
+ of an open SSE response in a worker, not even from the same isolate. What
336
+ crosses requests there is the store they share (D1 here), and the live side
337
+ re-reads it from inside its own request. See
338
+ [the Cloudflare example](../../examples/cloudflare).
339
+ - `Sync.transport.workerSocket` wraps the accepted end of a `WebSocketPair`
340
+ for `serveJournal`, anywhere else a platform hands one over.
341
+
282
342
  ## What makes a Message durable
283
343
 
284
344
  Replay runs a durable Message through `update` on another machine, later,
@@ -505,27 +565,50 @@ shows. `reset` is true when the server's history is a new one (a new
505
565
  `status.epoch`: the server was reset), so whatever the application derived
506
566
  from the old one, such as reads keyed by commit sequence, is to be read again.
507
567
 
568
+ `afterUpdate(model)` runs after every update of the mounted application, a
569
+ durable Message's and a reinstall's included, and never in replay. A durable
570
+ Message is replayed through `update` on the server and in the replica, where
571
+ it may change only the shared slice; local state derived from the slice (the
572
+ Remote overlays below) is kept in step here instead.
573
+
508
574
  ### Edit rows a server owns
509
575
 
510
576
  When rows are too many to replicate but edits to them must survive offline,
511
577
  let the journal own the edits and the table be its read model, each row
512
578
  carrying the highest sequence it has applied (`revision`). `foldkit-sync/entity`
513
- keeps such edits one per cell and lays them over the rows Remote reads:
579
+ keeps such edits one per cell, and `foldkit-sync/remote` shows them over the
580
+ rows Remote reads:
514
581
 
515
582
  ```text
516
- cell shown = the row's value, unless an edit of that cell is pending,
517
- or committed after the row's revision (at > row.revision)
583
+ cell shown = Remote's row, with each edit over it the row has not reached:
584
+ one pending, one committed after the row's revision, or one the
585
+ journal absorbed while the cached row is still below it
518
586
  ```
519
587
 
520
588
  `EditableEntity.make(Product, { members: ['description', 'cents'] })` gives
521
589
  the schemas (`Change` on the wire, `Edit` in the slice, the Message fields
522
590
  `edited` and `absorbed`) and pure functions for `update`, the stamp
523
- (`stamped`) and `onReinstall`: `merge`, `absorb`, `overlay` (for
524
- `RowModel.map`), `held` and `settled` (an edit the journal absorbed, kept until
525
- a read of its row reaches it), `replaced` (a cell of this tab's that another's
526
- later commit took), `cellsOf` (what a refusal undid) and `changeAt` (what a
527
- row holds in a member, as the change that sets it: an undo's value). It owns no state and
528
- does no I/O. On the server, `editsJournal` from `foldkit-sync/journal` keeps
591
+ (`stamped`) and `onReinstall`: `merge`, `absorb`, `replaced` (a cell of this
592
+ tab's that another's later commit took), `cellsOf` (what a refusal undid) and
593
+ `changeAt` (what a row holds in a member, as the change that sets it: an
594
+ undo's value). It owns no state and does no I/O.
595
+
596
+ `RemoteEdits.make(Data, ProductEdits)` is the bridge to a Remote domain over
597
+ the same Entity. Its `reconcile(model, edits, replica)` brings Remote's
598
+ overlays (`Data.overlay`) in line with the slice, so every read of a row draws
599
+ its edits, a second view or a filter as well as the grid. It holds an edit the
600
+ journal absorbed while the cached row is below it, and lifts it once a read
601
+ reaches it; it returns those newly `held` (ask for their rows again) and this
602
+ replica's edits a read reached with another value (`replaced`: the table
603
+ applies in commit order, so a later edit took the cell). An edit to a field a
604
+ list orders or filters by moves its row there at once, as Remote places any
605
+ pending edit. To see that when the
606
+ row arrives live after its own edit landed, it keeps this replica's landed
607
+ edit, showing the row's own value, until the slice drops it. Call it from
608
+ `afterUpdate`. `shown(model)` lists what the overlays show, for a cell's
609
+ mark, and `clear` lifts them all, for a reset. Remote stores none of it: after
610
+ a reload, `reconcile` rebuilds the overlays from the slice the replica
611
+ restored. On the server, `editsJournal` from `foldkit-sync/journal` keeps
529
612
  the table: its `settle` (for `journalExchange`) applies each committed change
530
613
  through your `apply` as a recovery intent, from the journal's floor and keyed
531
614
  by its epoch, and its `absorb` (on a clock) records what the table holds and
@@ -700,7 +783,11 @@ throttle? })` is a TTL'd peer registry outside the log: values are decoded befor
700
783
  they enter it, a peer that stops refreshing is pruned, and `throttle` sends at
701
784
  most one value per interval, the latest. `Sync.presence.socketChannel(transport.socket)`
702
785
  shares the sync socket across reconnects; `Sync.presence.hub` and `.serve` are
703
- the server side. [`examples/pages`](../../examples/pages) shows remote carets.
786
+ the server side. `.serve` stamps each frame with the connection's `peerId`, so a
787
+ peer cannot speak as another, and with `opens` (the exchange's own) joins only
788
+ a connection that may open the document, relaying nothing to or from one
789
+ refused. It asks again with each frame the connection sends, and one no
790
+ longer let open the document leaves. [`examples/pages`](../../examples/pages) shows remote carets.
704
791
 
705
792
  ### Last-writer-wins fields (experimental)
706
793
 
@@ -745,14 +832,15 @@ peer-to-peer merging, or migration of your own Messages and snapshots.
745
832
  implement.
746
833
  - One server order per document; no CRDT and no collaborative text algorithm.
747
834
  - Binding the socket transport to a platform WebSocket server is glue the
748
- examples show with `ws`.
835
+ examples show with `ws`; on workers, `foldkit-sync/do` defines the object
836
+ and `Sync.transport.workerSocket` wraps its accepted pair.
749
837
 
750
838
  ## Older spellings
751
839
 
752
840
  `Sync` groups the exports and wraps nothing; every name is also exported on its
753
841
  own with the same signature: `defineSync` is `Sync.define`, `syncMetrics` is
754
842
  `Sync.metrics`, `layerSocket`/`layerLoopback`/`layerFromPromise`/`toPromise`/
755
- `serveSocket`/`nativeSocket` are `Sync.transport.*`, `createPresence`/
843
+ `serveSocket`/`nativeSocket`/`workerSocket` are `Sync.transport.*`, `createPresence`/
756
844
  `createPresenceHub`/`servePresence`/`socketPresenceChannel`/
757
845
  `loopbackPresenceChannel` are `Sync.presence.*`, and `lwwRegister`/`openLwwClock`
758
846
  are `Sync.lww.*`. `documentId('todos')` and `DocumentId.make('todos')` make the
package/dist/do.d.mts ADDED
@@ -0,0 +1,60 @@
1
+ import { n as AuthorizeDecision, v as Operation, w as Sync } from "./make-h5yD8STj.mjs";
2
+ import { Effect } from "effect";
3
+ import { Journal } from "foldkit-durable/core";
4
+ //#region src/do.d.ts
5
+ /** The sliver of a Durable Object the host uses: state for the journal to open with. */
6
+ export interface DocumentHostContext {
7
+ readonly storage?: unknown;
8
+ }
9
+ /** What `defineDocumentHost` needs of the application, per document. */
10
+ export interface DocumentHostConfig<Message, Shared, Principal, Env> {
11
+ /** The document's contract: its codecs and journal shape. */
12
+ readonly sync: Sync<Message, Shared>;
13
+ /**
14
+ * Opens the document's journal, once: on the first upgrade, not on
15
+ * construction, so probes never provision storage. Over D1 (`d1: true`),
16
+ * or the object's SQLite storage through `ctx`. May build with Effect and
17
+ * unwrap; a rejection answers the upgrade with a 500, and the next upgrade
18
+ * tries again.
19
+ */
20
+ readonly openJournal: (ctx: DocumentHostContext, env: Env) => Promise<Journal<Operation, Shared, Principal, Operation>>;
21
+ /** Who is opening this socket, from the upgrade request. May throw: a 401. */
22
+ readonly resolvePrincipal: (request: Request, env: Env) => Principal | Promise<Principal>;
23
+ /**
24
+ * Runs after each exchange's appends and before the reply is read: apply
25
+ * what committed to another store, through `journal.recover`. Takes the
26
+ * environment — a D1 binding, say — and the journal, because both live
27
+ * outside the exchange. See `serveJournal`.
28
+ */
29
+ readonly settle?: ((env: Env, journal: Journal<Operation, Shared, Principal, Operation>) => Effect.Effect<void, unknown>) | undefined;
30
+ /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */
31
+ readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined;
32
+ /**
33
+ * Whether an operation from `principal` may be appended, before the journal
34
+ * sees it. See `journalExchange`'s `admit`.
35
+ */
36
+ readonly admit?: ((principal: Principal, operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>) | undefined;
37
+ /**
38
+ * Makes the socket pair for an upgrade: the server end is accepted before
39
+ * serving. Defaults to the `WebSocketPair` global where one exists (a
40
+ * worker, miniflare); pass one in tests.
41
+ */
42
+ readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined;
43
+ }
44
+ /**
45
+ * A server `WebSocket`: accepted once it serves. The `accept` member is a
46
+ * worker-runtime extension the DOM type does not declare.
47
+ */
48
+ export interface AcceptingWebSocket extends WebSocket {
49
+ accept(): void;
50
+ }
51
+ /**
52
+ * Defines the Durable Object class serving one document's Sync exchange.
53
+ * Non-upgrades are 404s that open nothing; a throwing principal resolution
54
+ * is a 401; a journal that never opened is a 500 that says nothing of it.
55
+ */
56
+ export declare const defineDocumentHost: <Message, Shared, Principal, Env>(Base: new (ctx: DocumentHostContext, env: Env) => object, config: DocumentHostConfig<Message, Shared, Principal, Env>) => new (ctx: DocumentHostContext, env: Env) => {
57
+ fetch(request: Request): Promise<Response>;
58
+ };
59
+ //#endregion
60
+ //# sourceMappingURL=do.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do.d.mts","names":[],"sources":["../src/do.ts"],"mappings":";;;;;iBAiCiB;WACN;;;iBAIM,mBAAmB,SAAS,QAAQ,WAAW;;WAErD,MAAM,KAAK,SAAS;;;;;;;;WAQpB,cACP,KAAK,qBACL,KAAK,QACF,QAAQ,QAAQ,WAAW,QAAQ,WAAW;;WAE1C,mBAAmB,SAAS,SAAS,KAAK,QAAQ,YAAY,QAAQ;;;;;;;WAOtE,WAEH,KAAK,KACL,SAAS,QAAQ,WAAW,QAAQ,WAAW,eAC5C,OAAO;;WAGP,UAAU,WAAW,cAAc,OAAO;;;;;WAK1C,UAEH,WAAW,WACX,WAAW,cACR,oBAAoB,OAAO,OAAO;;;;;;WAOlC,wBAAwB,QAAQ,WAAW,QAAQ;;;;;;iBAO7C,2BAA2B;EAC1C;;;;;;;qBAqBW,qBAAsB,SAAS,QAAQ,WAAW,KAC7D,WAAW,KAAK,qBAAqB,KAAK,gBAC1C,QAAQ,mBAAmB,SAAS,QAAQ,WAAW,cACjD,KAAK,qBAAqB,KAAK;EAAU,MAAM,SAAS,UAAU,QAAQ"}
package/dist/do.mjs ADDED
@@ -0,0 +1,59 @@
1
+ import { u as workerSocket } from "./transport-DiKXy5zx.mjs";
2
+ import { serveJournal } from "./journal.mjs";
3
+ //#region src/do.ts
4
+ const defaultPair = () => {
5
+ const maker = globalThis.WebSocketPair;
6
+ if (maker === void 0) throw new Error("DocumentHost: no WebSocketPair global; pass `pair` explicitly");
7
+ const pair = new maker();
8
+ return [pair[0], pair[1]];
9
+ };
10
+ /**
11
+ * Defines the Durable Object class serving one document's Sync exchange.
12
+ * Non-upgrades are 404s that open nothing; a throwing principal resolution
13
+ * is a 401; a journal that never opened is a 500 that says nothing of it.
14
+ */
15
+ const defineDocumentHost = (Base, config) => class extends Base {
16
+ hostContext;
17
+ hostEnv;
18
+ ready;
19
+ constructor(ctx, env) {
20
+ super(ctx, env);
21
+ this.hostContext = ctx;
22
+ this.hostEnv = env;
23
+ }
24
+ async fetch(request) {
25
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return Response.json({ error: "not found" }, { status: 404 });
26
+ let principal;
27
+ try {
28
+ principal = await config.resolvePrincipal(request, this.hostEnv);
29
+ } catch (error) {
30
+ return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 401 });
31
+ }
32
+ let journal;
33
+ try {
34
+ journal = await (this.ready ??= config.openJournal(this.hostContext, this.hostEnv));
35
+ } catch {
36
+ this.ready = void 0;
37
+ return Response.json({ error: "Internal error" }, { status: 500 });
38
+ }
39
+ const [client, server] = (config.pair ?? defaultPair)();
40
+ server.accept();
41
+ const { admit } = config;
42
+ serveJournal(workerSocket(server), {
43
+ sync: config.sync,
44
+ journal,
45
+ principal,
46
+ ...config.settle === void 0 ? {} : { settle: config.settle(this.hostEnv, journal) },
47
+ ...config.opens === void 0 ? {} : { opens: config.opens(principal) },
48
+ ...admit === void 0 ? {} : { admit: (operation) => admit(principal, operation) }
49
+ });
50
+ return new Response(null, {
51
+ status: 101,
52
+ webSocket: client
53
+ });
54
+ }
55
+ };
56
+ //#endregion
57
+ export { defineDocumentHost };
58
+
59
+ //# sourceMappingURL=do.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do.mjs","names":[],"sources":["../src/do.ts"],"sourcesContent":["/**\n * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare\n * Durable Object, the single writer its journal wants. Each socket the\n * object accepts exchanges against the same journal through `serveJournal`;\n * the replica side already exists as `Sync.transport.socket` over the\n * object's `wss://…` URL, which hears other writers' commits as notices.\n *\n * The class takes its `DurableObject` base as a parameter, so this module\n * imports no worker runtime and loads anywhere:\n *\n * ```ts\n * import { DurableObject } from 'cloudflare:workers'\n *\n * export class SyncHost extends defineDocumentHost(DurableObject, {\n * sync: Todos,\n * openJournal: (_ctx, env) => openTodosJournal(env.DB),\n * resolvePrincipal: request => ({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * }) {}\n * ```\n *\n * Open the journal once per object: on the first upgrade, so probes never\n * provision storage. Route one object per document (`idFromName(sync\n * .documentId)`); its in-memory cache and change stream are then exact\n * because nothing else writes.\n */\nimport type { Effect } from 'effect'\nimport type { Journal } from 'foldkit-durable/core'\nimport { serveJournal } from './journal.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync } from './sync.js'\nimport { workerSocket } from './transport.js'\n\n/** The sliver of a Durable Object the host uses: state for the journal to open with. */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** What `defineDocumentHost` needs of the application, per document. */\nexport interface DocumentHostConfig<Message, Shared, Principal, Env> {\n /** The document's contract: its codecs and journal shape. */\n readonly sync: Sync<Message, Shared>\n /**\n * Opens the document's journal, once: on the first upgrade, not on\n * construction, so probes never provision storage. Over D1 (`d1: true`),\n * or the object's SQLite storage through `ctx`. May build with Effect and\n * unwrap; a rejection answers the upgrade with a 500, and the next upgrade\n * tries again.\n */\n readonly openJournal: (\n ctx: DocumentHostContext,\n env: Env,\n ) => Promise<Journal<Operation, Shared, Principal, Operation>>\n /** Who is opening this socket, from the upgrade request. May throw: a 401. */\n readonly resolvePrincipal: (request: Request, env: Env) => Principal | Promise<Principal>\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. Takes the\n * environment — a D1 binding, say — and the journal, because both live\n * outside the exchange. See `serveJournal`.\n */\n readonly settle?:\n | ((\n env: Env,\n journal: Journal<Operation, Shared, Principal, Operation>,\n ) => Effect.Effect<void, unknown>)\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /**\n * Whether an operation from `principal` may be appended, before the journal\n * sees it. See `journalExchange`'s `admit`.\n */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * Makes the socket pair for an upgrade: the server end is accepted before\n * serving. Defaults to the `WebSocketPair` global where one exists (a\n * worker, miniflare); pass one in tests.\n */\n readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined\n}\n\n/**\n * A server `WebSocket`: accepted once it serves. The `accept` member is a\n * worker-runtime extension the DOM type does not declare.\n */\nexport interface AcceptingWebSocket extends WebSocket {\n accept(): void\n}\n\nconst defaultPair = (): readonly [client: WebSocket, server: AcceptingWebSocket] => {\n const maker = (\n globalThis as {\n readonly WebSocketPair?:\n (new () => { readonly 0: WebSocket; readonly 1: AcceptingWebSocket }) | undefined\n }\n ).WebSocketPair\n if (maker === undefined)\n throw new Error('DocumentHost: no WebSocketPair global; pass `pair` explicitly')\n const pair = new maker()\n return [pair[0], pair[1]] as const\n}\n\n/**\n * Defines the Durable Object class serving one document's Sync exchange.\n * Non-upgrades are 404s that open nothing; a throwing principal resolution\n * is a 401; a journal that never opened is a 500 that says nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env>,\n): new (ctx: DocumentHostContext, env: Env) => { fetch(request: Request): Promise<Response> } =>\n class extends Base {\n private readonly hostContext: DocumentHostContext\n private readonly hostEnv: Env\n private ready: Promise<Journal<Operation, Shared, Principal, Operation>> | undefined\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n this.hostContext = ctx\n this.hostEnv = env\n }\n\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket')\n return Response.json({ error: 'not found' }, { status: 404 })\n let principal: Principal\n try {\n principal = await config.resolvePrincipal(request, this.hostEnv)\n } catch (error) {\n return Response.json(\n { error: error instanceof Error ? error.message : String(error) },\n { status: 401 },\n )\n }\n let journal: Journal<Operation, Shared, Principal, Operation>\n try {\n journal = await (this.ready ??= config.openJournal(this.hostContext, this.hostEnv))\n } catch {\n // A failed open provisions nothing: the next upgrade tries again.\n this.ready = undefined\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n const [client, server] = (config.pair ?? defaultPair)()\n server.accept()\n const { admit } = config\n serveJournal(workerSocket(server), {\n sync: config.sync,\n journal,\n principal,\n ...(config.settle === undefined ? {} : { settle: config.settle(this.hostEnv, journal) }),\n ...(config.opens === undefined ? {} : { opens: config.opens(principal) }),\n ...(admit === undefined\n ? {}\n : { admit: (operation: Operation) => admit(principal, operation) }),\n })\n return new Response(null, {\n status: 101,\n // The worker runtime reads the client out of the upgrade response;\n // the DOM's `ResponseInit` has no such member.\n webSocket: client,\n } as ResponseInit)\n }\n }\n"],"mappings":";;;AA8FA,MAAM,oBAA8E;CAClF,MAAM,QACJ,WAIA;CACF,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,OAAO,IAAI,MAAM;CACvB,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;;AAOA,MAAa,sBACX,MACA,WAEA,cAAc,KAAK;CACjB;CACA;CACA;CAEA,YAAY,KAA0B,KAAU;EAC9C,MAAM,KAAK,GAAG;EACd,KAAK,cAAc;EACnB,KAAK,UAAU;CACjB;CAEA,MAAM,MAAM,SAAqC;EAC/C,IAAI,QAAQ,QAAQ,IAAI,SAAS,CAAC,EAAE,YAAY,MAAM,aACpD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;EAC9D,IAAI;EACJ,IAAI;GACF,YAAY,MAAM,OAAO,iBAAiB,SAAS,KAAK,OAAO;EACjE,SAAS,OAAO;GACd,OAAO,SAAS,KACd,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAChE,EAAE,QAAQ,IAAI,CAChB;EACF;EACA,IAAI;EACJ,IAAI;GACF,UAAU,OAAO,KAAK,UAAU,OAAO,YAAY,KAAK,aAAa,KAAK,OAAO;EACnF,QAAQ;GAEN,KAAK,QAAQ,KAAA;GACb,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;EACnE;EACA,MAAM,CAAC,QAAQ,WAAW,OAAO,QAAQ,YAAA,CAAa;EACtD,OAAO,OAAO;EACd,MAAM,EAAE,UAAU;EAClB,aAAa,aAAa,MAAM,GAAG;GACjC,MAAM,OAAO;GACb;GACA;GACA,GAAI,OAAO,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,OAAO,OAAO,KAAK,SAAS,OAAO,EAAE;GACtF,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,OAAO,MAAM,SAAS,EAAE;GACvE,GAAI,UAAU,KAAA,IACV,CAAC,IACD,EAAE,QAAQ,cAAyB,MAAM,WAAW,SAAS,EAAE;EACrE,CAAC;EACD,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ;GAGR,WAAW;EACb,CAAiB;CACnB;AACF"}
package/dist/entity.d.mts CHANGED
@@ -36,7 +36,7 @@ export type CellEdit<E extends EntityFields, Ms extends Member<E>> = { readonly
36
36
  readonly at: Option.Option<number>;
37
37
  readonly by: Option.Option<Author>;
38
38
  }; }[Ms];
39
- /** A row an overlay draws on: its id, the revision the table read it at, and its members. */
39
+ /** A row as the table holds it: its id, the revision it has applied, and its members. */
40
40
  export type RowOf<E extends EntityFields, Ms extends Member<E>> = {
41
41
  readonly id: IdOf<E>;
42
42
  readonly revision: number;
@@ -50,6 +50,8 @@ export interface Replaced<Edit> {
50
50
  declare const make: <E extends EntityFields, const Ms extends ReadonlyArray<Member<E>>>(entity: E, options: {
51
51
  readonly members: Ms;
52
52
  }) => {
53
+ /** Carried so `foldkit-sync/remote` can name the rows it overlays by the Entity's own name. */
54
+ entity: E;
53
55
  members: Ms;
54
56
  /** The members, as a schema: what names a cell. */
55
57
  Member: Schema.Literals<Ms>;
@@ -89,32 +91,6 @@ declare const make: <E extends EntityFields, const Ms extends ReadonlyArray<Memb
89
91
  absorb: (edits: ReadonlyArray<CellEdit<E, Ms[number]>>, through: number) => ReadonlyArray<CellEdit<E, Ms[number]>>;
90
92
  /** Whether any edit is committed through `through`: whether an absorb would drop one. */
91
93
  holdsThrough: (edits: ReadonlyArray<CellEdit<E, Ms[number]>>, through: number) => boolean;
92
- /** Whether the row, read at `revision`, does not hold the edit yet: shown over it. */
93
- shows: (edit: CellEdit<E, Ms[number]>, revision: number) => boolean;
94
- /**
95
- * The rows as shown: each with the edits it has not absorbed laid over it.
96
- * Built once per `edits`, for `RowModel.map`, which caches by its identity.
97
- */
98
- overlay: <R extends RowOf<E, Ms[number]>>(edits: ReadonlyArray<CellEdit<E, Ms[number]>>) => ((row: R) => R);
99
- /**
100
- * Of `edits`, the committed ones that `next` no longer holds, whose row is
101
- * cached below them: what the row would otherwise show stale. A row not
102
- * cached keeps nothing; its next read has the table's value.
103
- */
104
- held: (edits: ReadonlyArray<CellEdit<E, Ms[number]>>, next: ReadonlyArray<CellEdit<E, Ms[number]>>, revisionOf: (id: IdOf<E>) => Option.Option<number>) => ReadonlyArray<CellEdit<E, Ms[number]>>;
105
- /** Whether `after` holds a committed cell `before` did not: one just taken from the slice. */
106
- newlyHeld: (before: ReadonlyArray<CellEdit<E, Ms[number]>>, after: ReadonlyArray<CellEdit<E, Ms[number]>>) => boolean;
107
- /**
108
- * The held edits a read of their rows has reached, let go; of those,
109
- * `replica`'s own that the row shows another value for, as replaced: the
110
- * table applies in order, so a row at or past an edit that holds another
111
- * value took a later one, whose author the journal has absorbed. With
112
- * nothing reached, `held` comes back as it was given.
113
- */
114
- settled: (held: ReadonlyArray<CellEdit<E, Ms[number]>>, rowOf: (id: IdOf<E>) => Option.Option<RowOf<E, Ms[number]>>, replica: string) => {
115
- readonly held: ReadonlyArray<CellEdit<E, Ms[number]>>;
116
- readonly replaced: ReadonlyArray<Replaced<CellEdit<E, Ms[number]>>>;
117
- };
118
94
  /**
119
95
  * What the slice replaced that `replica` had written: each cell whose
120
96
  * edit was its own, and now holds another replica's commit with another
@@ -140,6 +116,8 @@ export declare const EditableEntity: {
140
116
  make: <E extends EntityFields, const Ms extends ReadonlyArray<Member<E>>>(entity: E, options: {
141
117
  readonly members: Ms;
142
118
  }) => {
119
+ /** Carried so `foldkit-sync/remote` can name the rows it overlays by the Entity's own name. */
120
+ entity: E;
143
121
  members: Ms;
144
122
  /** The members, as a schema: what names a cell. */
145
123
  Member: Schema.Literals<Ms>;
@@ -179,32 +157,6 @@ export declare const EditableEntity: {
179
157
  absorb: (edits: ReadonlyArray<CellEdit<E, Ms[number]>>, through: number) => ReadonlyArray<CellEdit<E, Ms[number]>>;
180
158
  /** Whether any edit is committed through `through`: whether an absorb would drop one. */
181
159
  holdsThrough: (edits: ReadonlyArray<CellEdit<E, Ms[number]>>, through: number) => boolean;
182
- /** Whether the row, read at `revision`, does not hold the edit yet: shown over it. */
183
- shows: (edit: CellEdit<E, Ms[number]>, revision: number) => boolean;
184
- /**
185
- * The rows as shown: each with the edits it has not absorbed laid over it.
186
- * Built once per `edits`, for `RowModel.map`, which caches by its identity.
187
- */
188
- overlay: <R extends RowOf<E, Ms[number]>>(edits: ReadonlyArray<CellEdit<E, Ms[number]>>) => ((row: R) => R);
189
- /**
190
- * Of `edits`, the committed ones that `next` no longer holds, whose row is
191
- * cached below them: what the row would otherwise show stale. A row not
192
- * cached keeps nothing; its next read has the table's value.
193
- */
194
- held: (edits: ReadonlyArray<CellEdit<E, Ms[number]>>, next: ReadonlyArray<CellEdit<E, Ms[number]>>, revisionOf: (id: IdOf<E>) => Option.Option<number>) => ReadonlyArray<CellEdit<E, Ms[number]>>;
195
- /** Whether `after` holds a committed cell `before` did not: one just taken from the slice. */
196
- newlyHeld: (before: ReadonlyArray<CellEdit<E, Ms[number]>>, after: ReadonlyArray<CellEdit<E, Ms[number]>>) => boolean;
197
- /**
198
- * The held edits a read of their rows has reached, let go; of those,
199
- * `replica`'s own that the row shows another value for, as replaced: the
200
- * table applies in order, so a row at or past an edit that holds another
201
- * value took a later one, whose author the journal has absorbed. With
202
- * nothing reached, `held` comes back as it was given.
203
- */
204
- settled: (held: ReadonlyArray<CellEdit<E, Ms[number]>>, rowOf: (id: IdOf<E>) => Option.Option<RowOf<E, Ms[number]>>, replica: string) => {
205
- readonly held: ReadonlyArray<CellEdit<E, Ms[number]>>;
206
- readonly replaced: ReadonlyArray<Replaced<CellEdit<E, Ms[number]>>>;
207
- };
208
160
  /**
209
161
  * What the slice replaced that `replica` had written: each cell whose
210
162
  * edit was its own, and now holds another replica's commit with another
@@ -1 +1 @@
1
- {"version":3,"file":"entity.d.mts","names":[],"sources":["../src/entity.ts"],"mappings":";;;qBA0Ba,QAAM,OAAA;;;;YACP,gBAAgB,OAAO;;iBAGlB;WACN;aAAmB;eAAe,QAAQ,OAAO;;;cAC9C;eAA4B,QAAQ,OAAO;;;;;YAK7C,OAAO,UAAU,gBAAgB,cAAc;KACtD,QAAQ,UAAU,cAAc,UAAU,OAAO,MAAM,YAAY;KACnE,KAAK,UAAU,gBAAgB;;YAGxB,OAAO,UAAU,cAAc,WAAW,OAAO,kBACjD,KAAK;WAAgB,IAAI,KAAK;WAAa,QAAQ;WAAY,OAAO,QAAQ,GAAG;KAC3F;;YAGU,SAAS,UAAU,cAAc,WAAW,OAAO,kBACnD,KAAK;WACJ,IAAI,KAAK;WACT,QAAQ;WACR,OAAO,QAAQ,GAAG;WAClB,IAAI,OAAO;WACX,IAAI,OAAO,OAAO;KAE7B;;YAGU,MAAM,UAAU,cAAc,WAAW,OAAO;WACjD,IAAI,KAAK;WACT;gBACK,KAAK,KAAK,QAAQ,GAAG;;iBAGpB,SAAS;WACf,MAAM;;WAEN,IAAI,OAAO,OAAO;;cAGvB,OAAQ,UAAU,oBAAoB,WAAW,cAAc,OAAO,KAC1E,QAAQ,GACR;WAAoB,SAAS;;;;;;;;;;;;;;;;;;;;;;;;EA0ET,UAAA;aACP;aACA;aACA;;;;;;;;;EAKF,QAAA,OAAA,cAAa,SAAA,GAAA,cAAM,SACjB,cAAc,OAAO,GAAC,cAAK,IAChC,OAAO,gBAAc,IACrB,OAAO,OAAO,YACjB,cAAa,SAAA,GAAA;;EAOA,SAAA,OAAA,cAAa,SAAA,GAAA,cAAM,oBAAoB,cAAa,SAAA,GAAA;;EAM9C,eAAA,OAAA,cAAa,SAAA,GAAA,cAAM;;EAIX,QAAA,MAAA,SAAA,GAAA,aAAA;;;;;EAMpB,UAAA,UAAC,MAAA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qBAuGxB;EA3JC,OAAA,UAAU,oBAAoB,WAAW,cAAc,OAAO,KAAG,QACrE,GAAC;aACW,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;IA4ET,UAAA;eACP;eACA;eACA;;;;;;;;;IAKF,QAAA,OAAA,cAAa,SAAA,GAAA,cAAM,SACjB,cAAc,OAAO,GAAC,cAAK,IAChC,OAAO,gBAAc,IACrB,OAAO,OAAO,YACjB,cAAa,SAAA,GAAA;;IAOA,SAAA,OAAA,cAAa,SAAA,GAAA,cAAM,oBAAoB,cAAa,SAAA,GAAA;;IAM9C,eAAA,OAAA,cAAa,SAAA,GAAA,cAAM;;;;;;IAS7B,WAAA,UAAA,cAAa,SAAA,GAAA,cAAM,MACvB,cAAa,SAAA,GAAA,cAAM,oBAExB,cAAc,SAAQ,SAAA,GAAA;;IAiBd,UAAA,SAAA,cAAc,OAAO,GAAC,iBAC9B;eAAyB,IAAI,KAAK;eAAa,QAAM;;;;;;IAOvB,WAAA,KAAA,MAAA,GAAA,aAAA,QAAA,eAAA,OAAO,GAAC;;IAKzB,SAAA,OAAA,cAAa,SAAA,GAAA,cAAM,KAAO,KAAK,IAAE,QAAA,eAAc,OAAO,OAAM,SAAA,GAAA;IA7F3C,OAAA,MAAA,SAAA,GAAA,aAAA;;;YAwGzB,eACV,UAAU,cACV,WAAW,cAAc,OAAO,OAC9B,kBAAkB,KAAK,GAAG"}
package/dist/entity.mjs CHANGED
@@ -2,22 +2,14 @@ import { Equal, Option, Schema } from "effect";
2
2
  //#region src/entity.ts
3
3
  /**
4
4
  * `foldkit-sync/entity`: edits to rows a server owns, kept in a replicated
5
- * slice that the journal owns, and laid over the rows Remote reads.
6
- *
7
- * ```text
8
- * cell shown = the row's value, unless an edit of that cell is pending,
9
- * or committed after the row's revision (at > row.revision)
10
- * ```
5
+ * slice that the journal owns. `foldkit-sync/remote` shows them over the rows
6
+ * Remote reads.
11
7
  *
12
8
  * The journal orders the edits and stamps each with the sequence it
13
9
  * committed at (`at`) and who committed it from where (`by`); the table is
14
10
  * the journal's read model, each row carrying the highest sequence it has
15
11
  * applied (`revision`). An edit the table holds is absorbed: the server says
16
- * so (`absorbed`), every replica drops it, and the journal compacts. A page
17
- * keeps a dropped edit (`held`) while a row it has cached is below it, so the
18
- * row never shows the stale read, and lets it go once a read of the row is at
19
- * or past it (`settled`), noting when the row then holds another value, a
20
- * later edit's.
12
+ * so (`absorbed`), every replica drops it, and the journal compacts.
21
13
  *
22
14
  * Everything here is pure: it owns no state, does no I/O, and sends nothing.
23
15
  * The application keeps the edits in its Model and calls these from
@@ -65,6 +57,8 @@ const make = (entity, options) => {
65
57
  onSome: () => Option.exists(edit.by, (by) => by.replica === replica)
66
58
  });
67
59
  return {
60
+ /** Carried so `foldkit-sync/remote` can name the rows it overlays by the Entity's own name. */
61
+ entity,
68
62
  members,
69
63
  /** The members, as a schema: what names a cell. */
70
64
  Member: Schema.Literals(members),
@@ -103,61 +97,6 @@ const make = (entity, options) => {
103
97
  absorb: (edits, through) => edits.some((edit) => reached(edit, through)) ? edits.filter((edit) => !reached(edit, through)) : edits,
104
98
  /** Whether any edit is committed through `through`: whether an absorb would drop one. */
105
99
  holdsThrough: (edits, through) => edits.some((edit) => reached(edit, through)),
106
- /** Whether the row, read at `revision`, does not hold the edit yet: shown over it. */
107
- shows: (edit, revision) => !reached(edit, revision),
108
- /**
109
- * The rows as shown: each with the edits it has not absorbed laid over it.
110
- * Built once per `edits`, for `RowModel.map`, which caches by its identity.
111
- */
112
- overlay: (edits) => {
113
- const index = indexOf(edits);
114
- return (row) => {
115
- const cells = index.get(row.id);
116
- if (cells === void 0) return row;
117
- let shown = row;
118
- for (const edit of cells.values()) if (!reached(edit, row.revision)) shown = {
119
- ...shown,
120
- [edit.member]: edit.value
121
- };
122
- return shown;
123
- };
124
- },
125
- /**
126
- * Of `edits`, the committed ones that `next` no longer holds, whose row is
127
- * cached below them: what the row would otherwise show stale. A row not
128
- * cached keeps nothing; its next read has the table's value.
129
- */
130
- held: (edits, next, revisionOf) => {
131
- const current = indexOf(next);
132
- return edits.filter((edit) => Option.isSome(edit.at) && !current.get(edit.id)?.has(edit.member) && Option.exists(revisionOf(edit.id), (revision) => !reached(edit, revision)));
133
- },
134
- /** Whether `after` holds a committed cell `before` did not: one just taken from the slice. */
135
- newlyHeld: (before, after) => after.some((edit) => !before.some((kept) => sameCell(kept, edit) && Equal.equals(kept.at, edit.at))),
136
- /**
137
- * The held edits a read of their rows has reached, let go; of those,
138
- * `replica`'s own that the row shows another value for, as replaced: the
139
- * table applies in order, so a row at or past an edit that holds another
140
- * value took a later one, whose author the journal has absorbed. With
141
- * nothing reached, `held` comes back as it was given.
142
- */
143
- settled: (held, rowOf, replica) => {
144
- const replaced = [];
145
- const kept = held.filter((edit) => Option.match(rowOf(edit.id), {
146
- onNone: () => true,
147
- onSome: (row) => {
148
- if (!reached(edit, row.revision)) return true;
149
- if (mine(edit, replica) && !Equal.equals(row[edit.member], edit.value)) replaced.push({
150
- edit,
151
- by: Option.none()
152
- });
153
- return false;
154
- }
155
- }));
156
- return {
157
- held: kept.length === held.length ? held : kept,
158
- replaced
159
- };
160
- },
161
100
  /**
162
101
  * What the slice replaced that `replica` had written: each cell whose
163
102
  * edit was its own, and now holds another replica's commit with another
@@ -1 +1 @@
1
- {"version":3,"file":"entity.mjs","names":[],"sources":["../src/entity.ts"],"sourcesContent":["/**\n * `foldkit-sync/entity`: edits to rows a server owns, kept in a replicated\n * slice that the journal owns, and laid over the rows Remote reads.\n *\n * ```text\n * cell shown = the row's value, unless an edit of that cell is pending,\n * or committed after the row's revision (at > row.revision)\n * ```\n *\n * The journal orders the edits and stamps each with the sequence it\n * committed at (`at`) and who committed it from where (`by`); the table is\n * the journal's read model, each row carrying the highest sequence it has\n * applied (`revision`). An edit the table holds is absorbed: the server says\n * so (`absorbed`), every replica drops it, and the journal compacts. A page\n * keeps a dropped edit (`held`) while a row it has cached is below it, so the\n * row never shows the stale read, and lets it go once a read of the row is at\n * or past it (`settled`), noting when the row then holds another value, a\n * later edit's.\n *\n * Everything here is pure: it owns no state, does no I/O, and sends nothing.\n * The application keeps the edits in its Model and calls these from\n * `update`, the stamp, and `Sync.mount`'s `onReinstall`.\n */\nimport { Equal, Option, Schema } from 'effect'\n\n/** Who committed an edit: the actor, shown in words, and the replica (a tab), which says whose it is. */\nexport const Author = Schema.Struct({ actor: Schema.String, replica: Schema.String })\nexport type Author = typeof Author.Type\n\n/** What `make` reads of an Entity: each member's schema, `id` among them. */\nexport interface EntityFields {\n readonly fields: { readonly id: { readonly schema: Schema.Top } } & {\n readonly [member: string]: { readonly schema: Schema.Top }\n }\n}\n\n/** The members an edit can change: every field but `id`. */\nexport type Member<E extends EntityFields> = Exclude<keyof E['fields'] & string, 'id'>\ntype ValueOf<E extends EntityFields, K extends Member<E>> = E['fields'][K]['schema']['Type']\ntype IdOf<E extends EntityFields> = E['fields']['id']['schema']['Type']\n\n/** One cell's new value: the member and a value of that member's type, together. */\nexport type Change<E extends EntityFields, Ms extends Member<E>> = {\n readonly [K in Ms]: { readonly id: IdOf<E>; readonly member: K; readonly value: ValueOf<E, K> }\n}[Ms]\n\n/** A cell's edit as the slice keeps it: committed `at` by `by`, or, with neither, pending. */\nexport type CellEdit<E extends EntityFields, Ms extends Member<E>> = {\n readonly [K in Ms]: {\n readonly id: IdOf<E>\n readonly member: K\n readonly value: ValueOf<E, K>\n readonly at: Option.Option<number>\n readonly by: Option.Option<Author>\n }\n}[Ms]\n\n/** A row an overlay draws on: its id, the revision the table read it at, and its members. */\nexport type RowOf<E extends EntityFields, Ms extends Member<E>> = {\n readonly id: IdOf<E>\n readonly revision: number\n} & { readonly [K in Ms]: ValueOf<E, K> }\n\n/** A cell this replica last wrote that a later edit replaced: its edit, and what the cell holds now. */\nexport interface Replaced<Edit> {\n readonly edit: Edit\n /** The later edit's author, when the slice still says; none once the journal absorbed it. */\n readonly by: Option.Option<Author>\n}\n\nconst make = <E extends EntityFields, const Ms extends ReadonlyArray<Member<E>>>(\n entity: E,\n options: { readonly members: Ms },\n) => {\n type M = Ms[number]\n type Edit = CellEdit<E, M>\n type Row = RowOf<E, M>\n const { members } = options\n const id = entity.fields.id.schema\n if (members.length === 0) throw new Error('EditableEntity.make: name at least one member')\n for (const member of members) {\n if ((member as string) === 'id' || !Object.hasOwn(entity.fields, member)) {\n throw new Error(`EditableEntity.make: ${member} is not a member of the entity`)\n }\n }\n const schemaOf = (member: M) => entity.fields[member]!.schema\n // One struct per member, so a value is decoded by its own member's schema:\n // the union is exactly `Change`, member and value paired.\n const Change = Schema.Union(\n members.map(member =>\n Schema.Struct({ id, member: Schema.Literal(member), value: schemaOf(member) }),\n ),\n ) as unknown as Schema.Codec<Change<E, M>, unknown>\n const Edit = Schema.Union(\n members.map(member =>\n Schema.Struct({\n id,\n member: Schema.Literal(member),\n value: schemaOf(member),\n at: Schema.OptionFromNullOr(Schema.Number),\n by: Schema.OptionFromNullOr(Author),\n }),\n ),\n ) as unknown as Schema.Codec<Edit, unknown>\n\n /** The edits by row, then member: no key is a string built from an id. */\n const indexOf = (edits: ReadonlyArray<Edit>) => {\n const index = new Map<IdOf<E>, Map<M, Edit>>()\n for (const edit of edits) {\n const row = index.get(edit.id) ?? new Map<M, Edit>()\n row.set(edit.member, edit)\n index.set(edit.id, row)\n }\n return index\n }\n const sameCell = (a: { readonly id: IdOf<E>; readonly member: M }, b: typeof a) =>\n Equal.equals(a.id, b.id) && a.member === b.member\n\n /** Whether a row read at `revision` has the edit: the table applies in the journal's order. */\n const reached = (edit: Edit, revision: number) => Option.exists(edit.at, at => at <= revision)\n\n /** Whether `replica` wrote the edit: pending here, or committed from it. */\n const mine = (edit: Edit, replica: string): boolean =>\n Option.match(edit.at, {\n onNone: () => true,\n onSome: () => Option.exists(edit.by, by => by.replica === replica),\n })\n\n return {\n members,\n /** The members, as a schema: what names a cell. */\n Member: Schema.Literals(members),\n /** One cell's change, on the wire: its member's value, by that member's schema. */\n Change,\n /** One cell's edit as the slice keeps it; `null` on the wire where it has no `at` or `by`. */\n Edit,\n /** The durable Message that edits cells: its fields, for the application's own tag. */\n edited: {\n changes: Schema.Array(Change),\n /** The journal's: absent on what a replica sends, stamped at commit. */\n at: Schema.optionalKey(Schema.Number),\n by: Schema.optionalKey(Author),\n },\n /** The server's durable Message: the table holds every edit committed through `through`. */\n absorbed: { through: Schema.Number },\n /** What the stamp writes into an edit: the sequence and the author. */\n stamped: (commit: {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n }) => ({ at: commit.sequence, by: { actor: commit.actorId, replica: commit.replicaId } }),\n\n /** The edits with `changes` laid over them, each cell's latest kept. */\n merge: (\n edits: ReadonlyArray<Edit>,\n changes: ReadonlyArray<Change<E, M>>,\n at: Option.Option<number>,\n by: Option.Option<Author>,\n ): ReadonlyArray<Edit> => {\n if (changes.length === 0) return edits\n const added = changes.map(change => ({ ...change, at, by }) as Edit)\n return [...edits.filter(edit => !added.some(next => sameCell(edit, next))), ...added]\n },\n\n /** The edits less those committed through `through`; the same array when none was. */\n absorb: (edits: ReadonlyArray<Edit>, through: number): ReadonlyArray<Edit> =>\n edits.some(edit => reached(edit, through))\n ? edits.filter(edit => !reached(edit, through))\n : edits,\n\n /** Whether any edit is committed through `through`: whether an absorb would drop one. */\n holdsThrough: (edits: ReadonlyArray<Edit>, through: number): boolean =>\n edits.some(edit => reached(edit, through)),\n\n /** Whether the row, read at `revision`, does not hold the edit yet: shown over it. */\n shows: (edit: Edit, revision: number): boolean => !reached(edit, revision),\n\n /**\n * The rows as shown: each with the edits it has not absorbed laid over it.\n * Built once per `edits`, for `RowModel.map`, which caches by its identity.\n */\n overlay: <R extends Row>(edits: ReadonlyArray<Edit>): ((row: R) => R) => {\n const index = indexOf(edits)\n return (row: R): R => {\n const cells = index.get(row.id)\n if (cells === undefined) return row\n let shown = row\n for (const edit of cells.values()) {\n if (!reached(edit, row.revision)) shown = { ...shown, [edit.member]: edit.value }\n }\n return shown\n }\n },\n\n /**\n * Of `edits`, the committed ones that `next` no longer holds, whose row is\n * cached below them: what the row would otherwise show stale. A row not\n * cached keeps nothing; its next read has the table's value.\n */\n held: (\n edits: ReadonlyArray<Edit>,\n next: ReadonlyArray<Edit>,\n revisionOf: (id: IdOf<E>) => Option.Option<number>,\n ): ReadonlyArray<Edit> => {\n const current = indexOf(next)\n return edits.filter(\n edit =>\n Option.isSome(edit.at) &&\n !current.get(edit.id)?.has(edit.member) &&\n Option.exists(revisionOf(edit.id), revision => !reached(edit, revision)),\n )\n },\n\n /** Whether `after` holds a committed cell `before` did not: one just taken from the slice. */\n newlyHeld: (before: ReadonlyArray<Edit>, after: ReadonlyArray<Edit>): boolean =>\n after.some(\n edit => !before.some(kept => sameCell(kept, edit) && Equal.equals(kept.at, edit.at)),\n ),\n\n /**\n * The held edits a read of their rows has reached, let go; of those,\n * `replica`'s own that the row shows another value for, as replaced: the\n * table applies in order, so a row at or past an edit that holds another\n * value took a later one, whose author the journal has absorbed. With\n * nothing reached, `held` comes back as it was given.\n */\n settled: (\n held: ReadonlyArray<Edit>,\n rowOf: (id: IdOf<E>) => Option.Option<Row>,\n replica: string,\n ): { readonly held: ReadonlyArray<Edit>; readonly replaced: ReadonlyArray<Replaced<Edit>> } => {\n const replaced: Array<Replaced<Edit>> = []\n const kept = held.filter(edit =>\n Option.match(rowOf(edit.id), {\n onNone: () => true,\n onSome: row => {\n if (!reached(edit, row.revision)) return true\n if (mine(edit, replica) && !Equal.equals(row[edit.member], edit.value)) {\n replaced.push({ edit, by: Option.none() })\n }\n return false\n },\n }),\n )\n return { held: kept.length === held.length ? held : kept, replaced }\n },\n\n /**\n * What the slice replaced that `replica` had written: each cell whose\n * edit was its own, and now holds another replica's commit with another\n * value, though it be the same person's in another tab.\n */\n replaced: (\n previous: ReadonlyArray<Edit>,\n next: ReadonlyArray<Edit>,\n replica: string,\n ): ReadonlyArray<Replaced<Edit>> => {\n const before = indexOf(previous)\n return next.flatMap(edit => {\n const prior = before.get(edit.id)?.get(edit.member)\n if (prior === undefined || !mine(prior, replica)) return []\n return Option.match(edit.by, {\n onNone: () => [],\n onSome: by =>\n by.replica !== replica && !Equal.equals(edit.value, prior.value)\n ? [{ edit: prior, by: Option.some(by) }]\n : [],\n })\n })\n },\n\n /** The cells a set of changes names: what a refusal of them undid. */\n cellsOf: (\n changes: ReadonlyArray<Change<E, M>>,\n ): ReadonlyArray<{ readonly id: IdOf<E>; readonly member: M }> =>\n changes.map(({ id: row, member }) => ({ id: row, member })),\n\n /**\n * What a row holds in one member, as the change that would set it: the\n * value an undo puts back.\n */\n changeAt: (row: Row, member: M): Change<E, M> =>\n // The member and its value are read together, so they pair as `Change` does.\n ({ id: row.id, member, value: row[member] }) as Change<E, M>,\n\n /** The edit of one cell, if the edits hold one. */\n editOf: (edits: ReadonlyArray<Edit>, row: IdOf<E>, member: M): Option.Option<Edit> =>\n Option.fromUndefinedOr(\n edits.find(edit => Equal.equals(edit.id, row) && edit.member === member),\n ),\n\n mine,\n }\n}\n\n/** Edits to an Entity's members, kept per cell in a replicated slice and laid over its rows. */\nexport const EditableEntity = { make }\nexport type EditableEntity<\n E extends EntityFields,\n Ms extends ReadonlyArray<Member<E>>,\n> = ReturnType<typeof make<E, Ms>>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,SAAS,OAAO,OAAO;CAAE,OAAO,OAAO;CAAQ,SAAS,OAAO;AAAO,CAAC;AA4CpF,MAAM,QACJ,QACA,YACG;CAIH,MAAM,EAAE,YAAY;CACpB,MAAM,KAAK,OAAO,OAAO,GAAG;CAC5B,IAAI,QAAQ,WAAW,GAAG,MAAM,IAAI,MAAM,+CAA+C;CACzF,KAAK,MAAM,UAAU,SACnB,IAAK,WAAsB,QAAQ,CAAC,OAAO,OAAO,OAAO,QAAQ,MAAM,GACrE,MAAM,IAAI,MAAM,wBAAwB,OAAO,+BAA+B;CAGlF,MAAM,YAAY,WAAc,OAAO,OAAO,OAAO,CAAE;CAGvD,MAAM,SAAS,OAAO,MACpB,QAAQ,KA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AI,GAAG,KAAK,KAAK,WAAW,MAAM,CACzE;EAEF;CACF;AACF;;AAGA,MAAa,iBAAiB,EAAE,KAAK"}
1
+ {"version":3,"file":"entity.mjs","names":[],"sources":["../src/entity.ts"],"sourcesContent":["/**\n * `foldkit-sync/entity`: edits to rows a server owns, kept in a replicated\n * slice that the journal owns. `foldkit-sync/remote` shows them over the rows\n * Remote reads.\n *\n * The journal orders the edits and stamps each with the sequence it\n * committed at (`at`) and who committed it from where (`by`); the table is\n * the journal's read model, each row carrying the highest sequence it has\n * applied (`revision`). An edit the table holds is absorbed: the server says\n * so (`absorbed`), every replica drops it, and the journal compacts.\n *\n * Everything here is pure: it owns no state, does no I/O, and sends nothing.\n * The application keeps the edits in its Model and calls these from\n * `update`, the stamp, and `Sync.mount`'s `onReinstall`.\n */\nimport { Equal, Option, Schema } from 'effect'\n\n/** Who committed an edit: the actor, shown in words, and the replica (a tab), which says whose it is. */\nexport const Author = Schema.Struct({ actor: Schema.String, replica: Schema.String })\nexport type Author = typeof Author.Type\n\n/** What `make` reads of an Entity: each member's schema, `id` among them. */\nexport interface EntityFields {\n readonly fields: { readonly id: { readonly schema: Schema.Top } } & {\n readonly [member: string]: { readonly schema: Schema.Top }\n }\n}\n\n/** The members an edit can change: every field but `id`. */\nexport type Member<E extends EntityFields> = Exclude<keyof E['fields'] & string, 'id'>\ntype ValueOf<E extends EntityFields, K extends Member<E>> = E['fields'][K]['schema']['Type']\ntype IdOf<E extends EntityFields> = E['fields']['id']['schema']['Type']\n\n/** One cell's new value: the member and a value of that member's type, together. */\nexport type Change<E extends EntityFields, Ms extends Member<E>> = {\n readonly [K in Ms]: { readonly id: IdOf<E>; readonly member: K; readonly value: ValueOf<E, K> }\n}[Ms]\n\n/** A cell's edit as the slice keeps it: committed `at` by `by`, or, with neither, pending. */\nexport type CellEdit<E extends EntityFields, Ms extends Member<E>> = {\n readonly [K in Ms]: {\n readonly id: IdOf<E>\n readonly member: K\n readonly value: ValueOf<E, K>\n readonly at: Option.Option<number>\n readonly by: Option.Option<Author>\n }\n}[Ms]\n\n/** A row as the table holds it: its id, the revision it has applied, and its members. */\nexport type RowOf<E extends EntityFields, Ms extends Member<E>> = {\n readonly id: IdOf<E>\n readonly revision: number\n} & { readonly [K in Ms]: ValueOf<E, K> }\n\n/** A cell this replica last wrote that a later edit replaced: its edit, and what the cell holds now. */\nexport interface Replaced<Edit> {\n readonly edit: Edit\n /** The later edit's author, when the slice still says; none once the journal absorbed it. */\n readonly by: Option.Option<Author>\n}\n\nconst make = <E extends EntityFields, const Ms extends ReadonlyArray<Member<E>>>(\n entity: E,\n options: { readonly members: Ms },\n) => {\n type M = Ms[number]\n type Edit = CellEdit<E, M>\n type Row = RowOf<E, M>\n const { members } = options\n const id = entity.fields.id.schema\n if (members.length === 0) throw new Error('EditableEntity.make: name at least one member')\n for (const member of members) {\n if ((member as string) === 'id' || !Object.hasOwn(entity.fields, member)) {\n throw new Error(`EditableEntity.make: ${member} is not a member of the entity`)\n }\n }\n const schemaOf = (member: M) => entity.fields[member]!.schema\n // One struct per member, so a value is decoded by its own member's schema:\n // the union is exactly `Change`, member and value paired.\n const Change = Schema.Union(\n members.map(member =>\n Schema.Struct({ id, member: Schema.Literal(member), value: schemaOf(member) }),\n ),\n ) as unknown as Schema.Codec<Change<E, M>, unknown>\n const Edit = Schema.Union(\n members.map(member =>\n Schema.Struct({\n id,\n member: Schema.Literal(member),\n value: schemaOf(member),\n at: Schema.OptionFromNullOr(Schema.Number),\n by: Schema.OptionFromNullOr(Author),\n }),\n ),\n ) as unknown as Schema.Codec<Edit, unknown>\n\n /** The edits by row, then member: no key is a string built from an id. */\n const indexOf = (edits: ReadonlyArray<Edit>) => {\n const index = new Map<IdOf<E>, Map<M, Edit>>()\n for (const edit of edits) {\n const row = index.get(edit.id) ?? new Map<M, Edit>()\n row.set(edit.member, edit)\n index.set(edit.id, row)\n }\n return index\n }\n const sameCell = (a: { readonly id: IdOf<E>; readonly member: M }, b: typeof a) =>\n Equal.equals(a.id, b.id) && a.member === b.member\n\n /** Whether a row read at `revision` has the edit: the table applies in the journal's order. */\n const reached = (edit: Edit, revision: number) => Option.exists(edit.at, at => at <= revision)\n\n /** Whether `replica` wrote the edit: pending here, or committed from it. */\n const mine = (edit: Edit, replica: string): boolean =>\n Option.match(edit.at, {\n onNone: () => true,\n onSome: () => Option.exists(edit.by, by => by.replica === replica),\n })\n\n return {\n /** Carried so `foldkit-sync/remote` can name the rows it overlays by the Entity's own name. */\n entity,\n members,\n /** The members, as a schema: what names a cell. */\n Member: Schema.Literals(members),\n /** One cell's change, on the wire: its member's value, by that member's schema. */\n Change,\n /** One cell's edit as the slice keeps it; `null` on the wire where it has no `at` or `by`. */\n Edit,\n /** The durable Message that edits cells: its fields, for the application's own tag. */\n edited: {\n changes: Schema.Array(Change),\n /** The journal's: absent on what a replica sends, stamped at commit. */\n at: Schema.optionalKey(Schema.Number),\n by: Schema.optionalKey(Author),\n },\n /** The server's durable Message: the table holds every edit committed through `through`. */\n absorbed: { through: Schema.Number },\n /** What the stamp writes into an edit: the sequence and the author. */\n stamped: (commit: {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n }) => ({ at: commit.sequence, by: { actor: commit.actorId, replica: commit.replicaId } }),\n\n /** The edits with `changes` laid over them, each cell's latest kept. */\n merge: (\n edits: ReadonlyArray<Edit>,\n changes: ReadonlyArray<Change<E, M>>,\n at: Option.Option<number>,\n by: Option.Option<Author>,\n ): ReadonlyArray<Edit> => {\n if (changes.length === 0) return edits\n const added = changes.map(change => ({ ...change, at, by }) as Edit)\n return [...edits.filter(edit => !added.some(next => sameCell(edit, next))), ...added]\n },\n\n /** The edits less those committed through `through`; the same array when none was. */\n absorb: (edits: ReadonlyArray<Edit>, through: number): ReadonlyArray<Edit> =>\n edits.some(edit => reached(edit, through))\n ? edits.filter(edit => !reached(edit, through))\n : edits,\n\n /** Whether any edit is committed through `through`: whether an absorb would drop one. */\n holdsThrough: (edits: ReadonlyArray<Edit>, through: number): boolean =>\n edits.some(edit => reached(edit, through)),\n\n /**\n * What the slice replaced that `replica` had written: each cell whose\n * edit was its own, and now holds another replica's commit with another\n * value, though it be the same person's in another tab.\n */\n replaced: (\n previous: ReadonlyArray<Edit>,\n next: ReadonlyArray<Edit>,\n replica: string,\n ): ReadonlyArray<Replaced<Edit>> => {\n const before = indexOf(previous)\n return next.flatMap(edit => {\n const prior = before.get(edit.id)?.get(edit.member)\n if (prior === undefined || !mine(prior, replica)) return []\n return Option.match(edit.by, {\n onNone: () => [],\n onSome: by =>\n by.replica !== replica && !Equal.equals(edit.value, prior.value)\n ? [{ edit: prior, by: Option.some(by) }]\n : [],\n })\n })\n },\n\n /** The cells a set of changes names: what a refusal of them undid. */\n cellsOf: (\n changes: ReadonlyArray<Change<E, M>>,\n ): ReadonlyArray<{ readonly id: IdOf<E>; readonly member: M }> =>\n changes.map(({ id: row, member }) => ({ id: row, member })),\n\n /**\n * What a row holds in one member, as the change that would set it: the\n * value an undo puts back.\n */\n changeAt: (row: Row, member: M): Change<E, M> =>\n // The member and its value are read together, so they pair as `Change` does.\n ({ id: row.id, member, value: row[member] }) as Change<E, M>,\n\n /** The edit of one cell, if the edits hold one. */\n editOf: (edits: ReadonlyArray<Edit>, row: IdOf<E>, member: M): Option.Option<Edit> =>\n Option.fromUndefinedOr(\n edits.find(edit => Equal.equals(edit.id, row) && edit.member === member),\n ),\n\n mine,\n }\n}\n\n/** Edits to an Entity's members, kept per cell in a replicated slice and laid over its rows. */\nexport const EditableEntity = { make }\nexport type EditableEntity<\n E extends EntityFields,\n Ms extends ReadonlyArray<Member<E>>,\n> = ReturnType<typeof make<E, Ms>>\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAa,SAAS,OAAO,OAAO;CAAE,OAAO,OAAO;CAAQ,SAAS,OAAO;AAAO,CAAC;AA4CpF,MAAM,QACJ,QACA,YACG;CAIH,MAAM,EAAE,YAAY;CACpB,MAAM,KAAK,OAAO,OAAO,GAAG;CAC5B,IAAI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