foldkit-sync 0.12.4 → 0.13.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.
Files changed (82) hide show
  1. package/README.md +76 -24
  2. package/dist/diagnostics.d.ts +71 -0
  3. package/dist/diagnostics.d.ts.map +1 -0
  4. package/dist/diagnostics.js +67 -0
  5. package/dist/diagnostics.js.map +1 -0
  6. package/dist/{do.d.mts → do.d.ts} +12 -2
  7. package/dist/do.d.ts.map +1 -0
  8. package/dist/{do.mjs → do.js} +15 -9
  9. package/dist/do.js.map +1 -0
  10. package/dist/{entity.d.mts → entity.d.ts} +1 -1
  11. package/dist/entity.d.ts.map +1 -0
  12. package/dist/{entity.mjs → entity.js} +1 -1
  13. package/dist/entity.js.map +1 -0
  14. package/dist/errors.d.ts +91 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +75 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/ids.d.ts +30 -0
  19. package/dist/ids.d.ts.map +1 -0
  20. package/dist/ids.js +28 -0
  21. package/dist/ids.js.map +1 -0
  22. package/dist/index.d.ts +106 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +77 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/indexedDb.d.ts +62 -0
  27. package/dist/indexedDb.d.ts.map +1 -0
  28. package/dist/indexedDb.js +128 -0
  29. package/dist/indexedDb.js.map +1 -0
  30. package/dist/{journal.d.mts → journal.d.ts} +29 -5
  31. package/dist/journal.d.ts.map +1 -0
  32. package/dist/{journal-D5h-jqXE.mjs → journal.js} +43 -32
  33. package/dist/journal.js.map +1 -0
  34. package/dist/lww.d.ts +76 -0
  35. package/dist/lww.d.ts.map +1 -0
  36. package/dist/lww.js +121 -0
  37. package/dist/lww.js.map +1 -0
  38. package/dist/make.d.ts +162 -0
  39. package/dist/make.d.ts.map +1 -0
  40. package/dist/make.js +153 -0
  41. package/dist/make.js.map +1 -0
  42. package/dist/mount.d.ts +138 -0
  43. package/dist/mount.d.ts.map +1 -0
  44. package/dist/mount.js +344 -0
  45. package/dist/mount.js.map +1 -0
  46. package/dist/presence.d.ts +116 -0
  47. package/dist/presence.d.ts.map +1 -0
  48. package/dist/presence.js +277 -0
  49. package/dist/presence.js.map +1 -0
  50. package/dist/{remote.d.mts → remote.d.ts} +2 -2
  51. package/dist/remote.d.ts.map +1 -0
  52. package/dist/{remote.mjs → remote.js} +1 -1
  53. package/dist/remote.js.map +1 -0
  54. package/dist/revalidate.d.ts +6 -0
  55. package/dist/revalidate.d.ts.map +1 -0
  56. package/dist/revalidate.js +10 -0
  57. package/dist/revalidate.js.map +1 -0
  58. package/dist/sync.d.ts +276 -0
  59. package/dist/sync.d.ts.map +1 -0
  60. package/dist/sync.js +512 -0
  61. package/dist/sync.js.map +1 -0
  62. package/dist/transport.d.ts +151 -0
  63. package/dist/transport.d.ts.map +1 -0
  64. package/dist/{transport-BZ6utYmB.mjs → transport.js} +20 -30
  65. package/dist/transport.js.map +1 -0
  66. package/package.json +24 -24
  67. package/dist/do.d.mts.map +0 -1
  68. package/dist/do.mjs.map +0 -1
  69. package/dist/entity.d.mts.map +0 -1
  70. package/dist/entity.mjs.map +0 -1
  71. package/dist/index.d.mts +0 -397
  72. package/dist/index.d.mts.map +0 -1
  73. package/dist/index.mjs +0 -1613
  74. package/dist/index.mjs.map +0 -1
  75. package/dist/journal-D5h-jqXE.mjs.map +0 -1
  76. package/dist/journal.d.mts.map +0 -1
  77. package/dist/journal.mjs +0 -1
  78. package/dist/make-DJ0Q1SSc.d.mts +0 -702
  79. package/dist/make-DJ0Q1SSc.d.mts.map +0 -1
  80. package/dist/remote.d.mts.map +0 -1
  81. package/dist/remote.mjs.map +0 -1
  82. package/dist/transport-BZ6utYmB.mjs.map +0 -1
package/README.md CHANGED
@@ -163,16 +163,18 @@ the exchange loop.
163
163
 
164
164
  ```ts
165
165
  import { Effect, Scope } from 'effect'
166
- import { ReplicaId, Sync } from 'foldkit-sync'
166
+ import { Sync } from 'foldkit-sync'
167
167
 
168
168
  const container = document.getElementById('app')!
169
169
 
170
- // One IndexedDB database per document and tab; its connection lives for the page.
170
+ // This tab's store, kept across reloads; its connection lives for the page.
171
171
  const scope = Effect.runSync(Scope.make())
172
- const storage = Effect.runSync(
173
- Effect.provideService(Sync.indexedDb('todos/tab-1'), Scope.Scope, scope),
172
+ const replica = await Effect.runPromise(
173
+ Sync.tabStorage('todos').pipe(
174
+ Effect.flatMap(TodoSync.openReplica),
175
+ Effect.provideService(Scope.Scope, scope),
176
+ ),
174
177
  )
175
- const replica = Effect.runSync(TodoSync.openReplica(ReplicaId.make('tab-1'), storage))
176
178
 
177
179
  const mounted = Sync.mount(App, TodoSync, {
178
180
  replica,
@@ -194,11 +196,15 @@ mounted.dispatch(Message.CreatedTodo({ id: crypto.randomUUID(), title: 'Milk' })
194
196
 
195
197
  What each call does, and does not do:
196
198
 
197
- - **`Sync.indexedDb(name)`** opens one database. Name it by document and
198
- writer: two tabs on one name race, and the loser fails its write rather than
199
- merging two histories.
200
- - **`openReplica(id, storage)`** reads back the committed snapshot, cursor, and
201
- outbox saved last time, or starts empty. It does no network I/O.
199
+ - **`Sync.tabStorage('todos')`** opens this tab's IndexedDB store. Its key
200
+ lives in `sessionStorage`, so a reload reopens the store, unsent edits
201
+ included; a duplicated tab, which copies that key, opens a store of its own.
202
+ - **`openReplica(storage)`** reads back the committed snapshot, cursor, and
203
+ outbox saved last time, or starts empty. It does no network I/O. The
204
+ replica's id is the store's: read back, or minted for an empty store.
205
+ Operation ids are `replicaId:count`, so an id names one store, never a
206
+ person: a person's second browser under the same id would send ids the
207
+ journal already has. `{ replicaId }` names one for a test or a server.
202
208
  - **`Sync.mount(App, TodoSync, …)`** runs the ordinary Foldkit runtime with
203
209
  your `view` and `update`. A durable Message applies through `update` at once,
204
210
  then a Command persists it; if the persist fails, the edit is reverted and
@@ -257,6 +263,8 @@ an optional peer of this package):
257
263
  a notice after each commit, so its replica hears of others' edits.
258
264
  `journalExchange(options)` is the same exchange as a `TransportClient`, for
259
265
  `Sync.transport.fromPromise` in process; `journalChanges` the notice alone.
266
+ Both report to `diagnostics`, when given, since a notice is sent from
267
+ outside any Effect context.
260
268
  - **What cannot be taken is rejected by its id, not left to fail the
261
269
  exchange.** An operation whose message does not decode, that names another
262
270
  document, that `authorize` or `validate` refuses, or that reuses an id for
@@ -328,7 +336,8 @@ Sync.transport.socket({ url: 'wss://example.com/sync' })
328
336
  by failing with a `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`
329
337
  makes one): a 401 carrying its message. Non-upgrades are 404s that open
330
338
  nothing. A resolver that breaks, a `layer` that fails to build, or a
331
- journal that never opened, is a 500 that says nothing of it.
339
+ journal that never opened, is a 500 that says nothing of it to the caller;
340
+ the cause is reported as a `HostDefect` (see [Diagnostics](#diagnostics)).
332
341
  - A resolver that reads a service (a session store) takes it from
333
342
  `layer: env => Layer`, required exactly when the resolver needs one. It is
334
343
  built per upgrade and kept until the socket closes, so `revalidate` reads
@@ -430,10 +439,12 @@ error. The replica drops it and replays the rest; the mount re-installs the
430
439
  shared slice, and the field the user edited reverts. `onPersistenceFailure`
431
440
  does not run for this, since the local save succeeded. Watch `rejected` to
432
441
  explain the revert: `journalExchange` gives each rejection a reason, the
433
- `authorize` rule's own when it gave one, and otherwise a fixed sentence
434
- ("Not a valid operation"). It never sends an error's message, which may carry
435
- internals, so a rule a person should read about belongs in `authorize` with a
436
- `reason`, not in `validate`.
442
+ `authorize` rule's own when it gave one. Otherwise it gives a fixed sentence:
443
+ "Refused by the server" when `authorize` refused with none (a plain `false`),
444
+ and "Not a valid operation" when the operation failed (`validate` refused or
445
+ threw, `authorize` threw, or the reducer could not apply it). It never sends
446
+ an error's message, which may carry internals, so a rule a person should read
447
+ about belongs in `authorize` with a `reason`, not in `validate`.
437
448
 
438
449
  **Waiting for the server.** The Model shows an edit before the server has it.
439
450
  Something that must not report success until the edit is committed, an agent
@@ -662,7 +673,7 @@ const memoryStorage = (): Storage => {
662
673
  }
663
674
 
664
675
  const program = Effect.gen(function* () {
665
- const replica = yield* TodoSync.openReplica(ReplicaId.make('test'), memoryStorage())
676
+ const replica = yield* TodoSync.openReplica(memoryStorage())
666
677
  yield* replica.submit(Message.CreatedTodo({ id: 't1', title: 'Milk' }))
667
678
  yield* replica.synchronize
668
679
  return yield* replica.status
@@ -697,8 +708,9 @@ application come first.
697
708
  - **Local storage was evicted.** The replica starts at cursor 0 and catches up
698
709
  from the server, but edits that lived only in the outbox are gone. The
699
710
  outbox is user data, not a cache.
700
- - **Two tabs share one storage name.** Compare-and-swap fails the stale writer
701
- with `StorageError`. Give each tab its own name and `ReplicaId`.
711
+ - **Two tabs share one store.** Compare-and-swap fails the stale writer with
712
+ `StorageError`. `Sync.tabStorage` gives each tab its own; a store named by
713
+ hand with `Sync.indexedDb(name)` must be one tab's.
702
714
  - **The replica is far behind.** The server may answer in pages (`more`), and
703
715
  `synchronize` asks again at once until caught up. If the server compacted
704
716
  the history it needs, it sends a checkpoint instead: a snapshot and cursor
@@ -718,6 +730,38 @@ application come first.
718
730
  order, acknowledgements or rejections for operations the replica never sent:
719
731
  each fails the exchange rather than touch local work.
720
732
 
733
+ ### Diagnostics
734
+
735
+ What Sync keeps going past it reports as a typed diagnostic through
736
+ `Diagnostics.Reporter` (`foldkit-surface`'s channel), which by default is
737
+ Effect's log: the console in a browser, `wrangler tail` on a Worker.
738
+
739
+ | `_tag` | `level` | When |
740
+ | --- | --- | --- |
741
+ | `ExchangeFailed` | `warning` | An exchange failed; it is in `status.lastError` and retried on a backoff. Carries the `error`. |
742
+ | `HistoryRebuilt` | `warning` | The server answered from another epoch, so the committed state was rebuilt from it (the outbox is kept). |
743
+ | `HostDefect` | `error` | A document host broke on its side, at a `stage`: `Upgrade` (the socket pair), `Resolve` (the `layer` or resolver), `Journal`, `Exchange` (`opens` or `settle` threw) answer a 500; `Revalidate` closes the socket with 1011; `Notice` (`opens` failed before a commit notice) sends none; `Changes` (the journal's stream of commits broke) sends no more. Carries the `cause`, which the replica is never told. |
744
+ | `ListenerFailed` | `error` | A listener the application gave threw: a presence subscriber, a listener on the socket transport's shared `socket`, or `journalChanges`' listener (`Notice`, called again on the next commit). The others still ran. |
745
+
746
+ A replica reports to the reporter in the Effect context it runs in:
747
+ `Layer.succeed(Diagnostics.Reporter, report)` in the runtime's resources. A
748
+ host takes one with the upgrade request beside it, used for everything that
749
+ upgrade runs:
750
+
751
+ ```ts
752
+ export class SyncHost extends defineDocumentHost(DurableObject, {
753
+ sync: TodoSync,
754
+ openJournal: (_ctx, env) => openTodosJournal(env.DB),
755
+ resolvePrincipal: request => Effect.succeed(request.headers.get('x-actor') ?? 'anon'),
756
+ diagnostics: (diagnostic, request) =>
757
+ Effect.logError(`${request.url}: ${diagnostic.message}`),
758
+ }) {}
759
+ ```
760
+
761
+ `documentHost` takes the same `diagnostics`, and `serveJournal` a
762
+ `diagnostics` reporter of its own. In a test, `Diagnostics.collect()` gives a
763
+ reporter and the array it fills.
764
+
721
765
  ## Advanced: the replica
722
766
 
723
767
  `Sync.mount` is the normal path. Underneath, a `Replica` works on the shared
@@ -726,8 +770,8 @@ server-side actor, a test) uses it directly.
726
770
 
727
771
  ```ts
728
772
  const program = Effect.gen(function* () {
729
- const storage = yield* Sync.indexedDb('todos/tab-1')
730
- const replica = yield* TodoSync.openReplica(ReplicaId.make('tab-1'), storage)
773
+ const storage = yield* Sync.indexedDb('todos/worker')
774
+ const replica = yield* TodoSync.openReplica(storage)
731
775
 
732
776
  yield* replica.submit(Message.CreatedTodo({ id: 't1', title: 'Milk' }))
733
777
  const optimistic = yield* replica.shared // includes the pending edit
@@ -737,7 +781,10 @@ const program = Effect.gen(function* () {
737
781
  }).pipe(Effect.scoped, Effect.provide(Sync.transport.socket({ url: 'wss://example.com/sync' })))
738
782
  ```
739
783
 
740
- `submit(message)` checks that the Message is durable, replays it against the
784
+ `submit(message)` takes a durable Message: on a replica from
785
+ `Sync.forApplication(App).make`, a local one does not compile, and an
786
+ annotated export names the subset (`Sync<Message, Shared, Durable>`). It
787
+ checks again that the Message is durable, replays it against the
741
788
  current optimistic state, gives it a stable operation id, saves it to the
742
789
  outbox, publishes the new optimistic value, and wakes the loop. It sends
743
790
  nothing. A Message replay refuses never enters the outbox.
@@ -784,7 +831,9 @@ replica validates every field; see [when things go wrong](#when-things-go-wrong)
784
831
  new exchanges fast until a socket is healthy again. `maxQueue` (64) bounds
785
832
  the queue.
786
833
  Instead of a `url`, pass `makeSocket: () => SocketLike` to connect over
787
- something else; it is called again on each reconnect.
834
+ something else; it is called again on each reconnect. Beside `Transport` it
835
+ provides `TransportSocket`, the connection it keeps, for another protocol
836
+ to share; a layer without a socket has no `TransportSocket` in its type.
788
837
  - `Sync.transport.serve(socket, { exchange, changes? })`: the server side of one
789
838
  accepted socket. With `changes`, a subscription to the document's commits, it
790
839
  sends a notice after each; the client's loop exchanges on every notice, so a
@@ -806,8 +855,9 @@ A refusal is data in the answer; only a wire failure is a `TransportError`.
806
855
  does, not replay next week. `Sync.presence.make({ id, ttl, decodeValue, channel?,
807
856
  throttle? })` is a TTL'd peer registry outside the log: values are decoded before
808
857
  they enter it, a peer that stops refreshing is pruned, and `throttle` sends at
809
- most one value per interval, the latest. `Sync.presence.socketChannel(transport.socket)`
810
- shares the sync socket across reconnects; `Sync.presence.hub` and `.serve` are
858
+ most one value per interval, the latest. `Sync.presence.socketChannel(socket)`,
859
+ given the `TransportSocket` the socket transport provides, shares the sync
860
+ socket across reconnects; `Sync.presence.hub` and `.serve` are
811
861
  the server side. `.serve` stamps each frame with the connection's `peerId`, so a
812
862
  peer cannot speak as another, and with `opens` (the exchange's own) joins only
813
863
  a connection that may open the document, relaying nothing to or from one
@@ -875,6 +925,8 @@ same branded value, as do the other id constructors.
875
925
 
876
926
  - [Replicated state](../../docs/replication.md): both halves end to end, with
877
927
  the server's exchange handler.
928
+ - [Errors and failures](../../docs/errors.md): how a rejected edit or a failed
929
+ exchange sits beside Remote's, a form's and the server's failures.
878
930
  - [`foldkit-durable`](../durable): the journal and what it guarantees.
879
931
  - [Runtime binding](../../docs/sync-runtime-binding.md): what `Sync.mount` does
880
932
  inside the Foldkit runtime, for the curious.
@@ -0,0 +1,71 @@
1
+ import { Cause, Effect } from "effect";
2
+ import { Diagnostic, ReportDiagnostic } from "foldkit-surface";
3
+ import { TransportError } from "./transport.js";
4
+ import { ReplicaError } from "./errors.js";
5
+ /** An exchange failed; the replica shows it in `status.lastError` and tries again on a backoff. */
6
+ export interface ExchangeFailed extends Diagnostic {
7
+ readonly _tag: 'ExchangeFailed';
8
+ readonly documentId: string;
9
+ readonly replicaId: string;
10
+ readonly error: ReplicaError | TransportError;
11
+ }
12
+ /**
13
+ * The server answered from another epoch: its history is not the one the
14
+ * replica's cursor points into (it was reset), so the committed state was
15
+ * rebuilt from its answer. The outbox is kept.
16
+ */
17
+ export interface HistoryRebuilt extends Diagnostic {
18
+ readonly _tag: 'HistoryRebuilt';
19
+ readonly documentId: string;
20
+ readonly replicaId: string;
21
+ }
22
+ /** Where a document host broke. */
23
+ export type HostStage =
24
+ /** Making or accepting the socket pair (`foldkit-sync/do`). */
25
+ 'Upgrade' |
26
+ /** Building `layer`, or `resolvePrincipal` dying or throwing. */
27
+ 'Resolve' |
28
+ /** Opening the journal. */
29
+ 'Journal' |
30
+ /** The application's `opens` or `settle` throwing as the exchange was made. */
31
+ 'Exchange' |
32
+ /** `revalidate` asking the resolver again, which died: the socket closed with 1011. */
33
+ 'Revalidate' |
34
+ /** Asking `opens` before a commit notice, which failed: the notice was not sent. */
35
+ 'Notice' |
36
+ /** The journal's stream of commits, which broke: the connection hears of no more commits. */
37
+ 'Changes';
38
+ /**
39
+ * A document host broke on its own side: the upgrade was answered 500
40
+ * "Internal error", the socket closed with 1011, or a notice went unsent. The
41
+ * replica is told nothing of the cause.
42
+ */
43
+ export interface HostDefect extends Diagnostic {
44
+ readonly _tag: 'HostDefect';
45
+ readonly stage: HostStage;
46
+ readonly cause: Cause.Cause<unknown>;
47
+ }
48
+ /** Where a listener the application gave was called. */
49
+ export type ListenerSite =
50
+ /** `Presence.subscribe`'s listener, after a peer changed. */
51
+ 'Presence' |
52
+ /** A listener on the socket transport's shared `socket` (`onMessage`), for another protocol's frames. */
53
+ 'Socket' |
54
+ /** `journalChanges`' listener, after a commit: the next commit calls it again. */
55
+ 'Notice';
56
+ /** A listener the application gave threw; the rest still ran, and so did Sync. */
57
+ export interface ListenerFailed extends Diagnostic {
58
+ readonly _tag: 'ListenerFailed';
59
+ readonly site: ListenerSite;
60
+ /** What it threw. */
61
+ readonly thrown: unknown;
62
+ }
63
+ /** Every diagnostic Sync reports. */
64
+ export type SyncDiagnostic = ExchangeFailed | HistoryRebuilt | HostDefect | ListenerFailed;
65
+ export declare const exchangeFailed: (documentId: string, replicaId: string, error: ReplicaError | TransportError) => ExchangeFailed;
66
+ export declare const historyRebuilt: (documentId: string, replicaId: string) => HistoryRebuilt;
67
+ export declare const hostDefect: (stage: HostStage, cause: Cause.Cause<unknown>) => HostDefect;
68
+ export declare const listenerFailed: (site: ListenerSite, thrown: unknown) => ListenerFailed;
69
+ /** Reports `diagnostic` to `reporter` when a host gave one, else to the reporter in context. */
70
+ export declare const reportTo: (reporter: ReportDiagnostic | undefined, diagnostic: SyncDiagnostic) => Effect.Effect<void>;
71
+ //# sourceMappingURL=diagnostics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.d.ts","names":[],"sources":["../src/diagnostics.ts"],"mappings":";;;;;iBAgBiB,uBAAuB;WAC7B;WACA;WACA;WACA,OAAO,eAAe;;;;;;;iBAQhB,uBAAuB;WAC7B;WACA;WACA;;;YAIC;;;;;;;;;;;;;;;;;;;;iBAqBK,mBAAmB;WACzB;WACA,OAAO;WACP,OAAO,MAAM;;;YAIZ;;;;;;;;iBASK,uBAAuB;WAC7B;WACA,MAAM;;WAEN;;;YAIC,iBAAiB,iBAAiB,iBAAiB,aAAa;qBAE/D,iBAAc,oBACP,mBACD,OACV,eAAe,mBACrB;qBAUU,iBAAc,oBAAsB,sBAAsB;qBAoB1D,aAAU,OAAW,WAAS,OAAS,MAAM,mBAAiB;qBAe9D,iBAAc,MAAU,cAAY,oBAAoB;;qBAUxD,WAAQ,UACT,8BAA4B,YAC1B,mBACX,OAAO"}
@@ -0,0 +1,67 @@
1
+ import { Cause, Effect } from "effect";
2
+ import { Diagnostics } from "foldkit-surface";
3
+ // src/diagnostics.ts
4
+ /**
5
+ * What Sync meets and keeps going past. A replica whose exchange failed (also
6
+ * in `status.lastError`), or whose server's history changed under it; a
7
+ * document host that answered an upgrade "Internal error" or closed a socket
8
+ * as one, whose cause neither the replica nor the response carries; and a
9
+ * listener the application gave that threw. Each is reported through
10
+ * `Diagnostics.report`.
11
+ */
12
+ const source = "foldkit-sync";
13
+ const exchangeFailed = (documentId, replicaId, error) => ({
14
+ _tag: "ExchangeFailed",
15
+ source,
16
+ level: "warning",
17
+ message: `${documentId} (replica ${replicaId}) failed an exchange (${error._tag}: ${error.message}); it is in status.lastError and tried again on a backoff.`,
18
+ documentId,
19
+ replicaId,
20
+ error
21
+ });
22
+ const historyRebuilt = (documentId, replicaId) => ({
23
+ _tag: "HistoryRebuilt",
24
+ source,
25
+ level: "warning",
26
+ message: `${documentId} (replica ${replicaId}): the server's history changed (another epoch), so the committed state was rebuilt from it; unsent edits were kept.`,
27
+ documentId,
28
+ replicaId
29
+ });
30
+ const stageText = {
31
+ Upgrade: "making or accepting the socket broke, and the upgrade was answered \"Internal error\"",
32
+ Resolve: "building the layer or resolving the principal broke, and the upgrade was answered \"Internal error\"",
33
+ Journal: "opening the journal failed, and the upgrade was answered \"Internal error\"",
34
+ Exchange: "opens or settle threw, and the upgrade was answered \"Internal error\"",
35
+ Revalidate: "asking the resolver again broke, and the socket was closed with 1011",
36
+ Notice: "asking opens before a commit notice failed, and the notice was not sent",
37
+ Changes: "the journal's stream of commits broke, and this connection hears of no more commits"
38
+ };
39
+ const hostDefect = (stage, cause) => ({
40
+ _tag: "HostDefect",
41
+ source,
42
+ level: "error",
43
+ message: `a document host broke: ${stageText[stage]}\n${Cause.pretty(cause)}`,
44
+ stage,
45
+ cause
46
+ });
47
+ const siteText = {
48
+ Presence: "a presence listener",
49
+ Socket: "a listener on the replica's socket",
50
+ Notice: "the listener woken by a commit"
51
+ };
52
+ const listenerFailed = (site, thrown) => ({
53
+ _tag: "ListenerFailed",
54
+ source,
55
+ level: "error",
56
+ message: `${siteText[site]} threw (${String(thrown)}); the other listeners ran.`,
57
+ site,
58
+ thrown
59
+ });
60
+ /** Reports `diagnostic` to `reporter` when a host gave one, else to the reporter in context. */
61
+ const reportTo = (reporter, diagnostic) => {
62
+ const reported = Diagnostics.report(diagnostic);
63
+ return reporter === void 0 ? reported : Effect.provideService(reported, Diagnostics.Reporter, reporter);
64
+ };
65
+ export { exchangeFailed, historyRebuilt, hostDefect, listenerFailed, reportTo };
66
+
67
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * What Sync meets and keeps going past. A replica whose exchange failed (also\n * in `status.lastError`), or whose server's history changed under it; a\n * document host that answered an upgrade \"Internal error\" or closed a socket\n * as one, whose cause neither the replica nor the response carries; and a\n * listener the application gave that threw. Each is reported through\n * `Diagnostics.report`.\n */\nimport { Cause, Effect } from 'effect'\nimport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nimport type { ReplicaError } from './errors.js'\nimport type { TransportError } from './transport.js'\n\nconst source = 'foldkit-sync'\n\n/** An exchange failed; the replica shows it in `status.lastError` and tries again on a backoff. */\nexport interface ExchangeFailed extends Diagnostic {\n readonly _tag: 'ExchangeFailed'\n readonly documentId: string\n readonly replicaId: string\n readonly error: ReplicaError | TransportError\n}\n\n/**\n * The server answered from another epoch: its history is not the one the\n * replica's cursor points into (it was reset), so the committed state was\n * rebuilt from its answer. The outbox is kept.\n */\nexport interface HistoryRebuilt extends Diagnostic {\n readonly _tag: 'HistoryRebuilt'\n readonly documentId: string\n readonly replicaId: string\n}\n\n/** Where a document host broke. */\nexport type HostStage =\n /** Making or accepting the socket pair (`foldkit-sync/do`). */\n | 'Upgrade'\n /** Building `layer`, or `resolvePrincipal` dying or throwing. */\n | 'Resolve'\n /** Opening the journal. */\n | 'Journal'\n /** The application's `opens` or `settle` throwing as the exchange was made. */\n | 'Exchange'\n /** `revalidate` asking the resolver again, which died: the socket closed with 1011. */\n | 'Revalidate'\n /** Asking `opens` before a commit notice, which failed: the notice was not sent. */\n | 'Notice'\n /** The journal's stream of commits, which broke: the connection hears of no more commits. */\n | 'Changes'\n\n/**\n * A document host broke on its own side: the upgrade was answered 500\n * \"Internal error\", the socket closed with 1011, or a notice went unsent. The\n * replica is told nothing of the cause.\n */\nexport interface HostDefect extends Diagnostic {\n readonly _tag: 'HostDefect'\n readonly stage: HostStage\n readonly cause: Cause.Cause<unknown>\n}\n\n/** Where a listener the application gave was called. */\nexport type ListenerSite =\n /** `Presence.subscribe`'s listener, after a peer changed. */\n | 'Presence'\n /** A listener on the socket transport's shared `socket` (`onMessage`), for another protocol's frames. */\n | 'Socket'\n /** `journalChanges`' listener, after a commit: the next commit calls it again. */\n | 'Notice'\n\n/** A listener the application gave threw; the rest still ran, and so did Sync. */\nexport interface ListenerFailed extends Diagnostic {\n readonly _tag: 'ListenerFailed'\n readonly site: ListenerSite\n /** What it threw. */\n readonly thrown: unknown\n}\n\n/** Every diagnostic Sync reports. */\nexport type SyncDiagnostic = ExchangeFailed | HistoryRebuilt | HostDefect | ListenerFailed\n\nexport const exchangeFailed = (\n documentId: string,\n replicaId: string,\n error: ReplicaError | TransportError,\n): ExchangeFailed => ({\n _tag: 'ExchangeFailed',\n source,\n level: 'warning',\n message: `${documentId} (replica ${replicaId}) failed an exchange (${error._tag}: ${error.message}); it is in status.lastError and tried again on a backoff.`,\n documentId,\n replicaId,\n error,\n})\n\nexport const historyRebuilt = (documentId: string, replicaId: string): HistoryRebuilt => ({\n _tag: 'HistoryRebuilt',\n source,\n level: 'warning',\n message: `${documentId} (replica ${replicaId}): the server's history changed (another epoch), so the committed state was rebuilt from it; unsent edits were kept.`,\n documentId,\n replicaId,\n})\n\nconst stageText: Record<HostStage, string> = {\n Upgrade: 'making or accepting the socket broke, and the upgrade was answered \"Internal error\"',\n Resolve:\n 'building the layer or resolving the principal broke, and the upgrade was answered \"Internal error\"',\n Journal: 'opening the journal failed, and the upgrade was answered \"Internal error\"',\n Exchange: 'opens or settle threw, and the upgrade was answered \"Internal error\"',\n Revalidate: 'asking the resolver again broke, and the socket was closed with 1011',\n Notice: 'asking opens before a commit notice failed, and the notice was not sent',\n Changes: \"the journal's stream of commits broke, and this connection hears of no more commits\",\n}\n\nexport const hostDefect = (stage: HostStage, cause: Cause.Cause<unknown>): HostDefect => ({\n _tag: 'HostDefect',\n source,\n level: 'error',\n message: `a document host broke: ${stageText[stage]}\\n${Cause.pretty(cause)}`,\n stage,\n cause,\n})\n\nconst siteText: Record<ListenerSite, string> = {\n Presence: 'a presence listener',\n Socket: \"a listener on the replica's socket\",\n Notice: 'the listener woken by a commit',\n}\n\nexport const listenerFailed = (site: ListenerSite, thrown: unknown): ListenerFailed => ({\n _tag: 'ListenerFailed',\n source,\n level: 'error',\n message: `${siteText[site]} threw (${String(thrown)}); the other listeners ran.`,\n site,\n thrown,\n})\n\n/** Reports `diagnostic` to `reporter` when a host gave one, else to the reporter in context. */\nexport const reportTo = (\n reporter: ReportDiagnostic | undefined,\n diagnostic: SyncDiagnostic,\n): Effect.Effect<void> => {\n const reported = Diagnostics.report(diagnostic)\n return reporter === undefined\n ? reported\n : Effect.provideService(reported, Diagnostics.Reporter, reporter)\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAM,SAAS;AAqEf,MAAa,kBACX,YACA,WACA,WACoB;CACpB,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,YAAY,UAAU,wBAAwB,MAAM,KAAK,IAAI,MAAM,QAAQ;CAClG;CACA;CACA;AACF;AAEA,MAAa,kBAAkB,YAAoB,eAAuC;CACxF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,YAAY,UAAU;CAC7C;CACA;AACF;AAEA,MAAM,YAAuC;CAC3C,SAAS;CACT,SACE;CACF,SAAS;CACT,UAAU;CACV,YAAY;CACZ,QAAQ;CACR,SAAS;AACX;AAEA,MAAa,cAAc,OAAkB,WAA6C;CACxF,MAAM;CACN;CACA,OAAO;CACP,SAAS,0BAA0B,UAAU,OAAO,IAAI,MAAM,OAAO,KAAK;CAC1E;CACA;AACF;AAEA,MAAM,WAAyC;CAC7C,UAAU;CACV,QAAQ;CACR,QAAQ;AACV;AAEA,MAAa,kBAAkB,MAAoB,YAAqC;CACtF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,SAAS,MAAM,UAAU,OAAO,MAAM,EAAE;CACpD;CACA;AACF;;AAGA,MAAa,YACX,UACA,eACwB;CACxB,MAAM,WAAW,YAAY,OAAO,UAAU;CAC9C,OAAO,aAAa,KAAA,IAChB,WACA,OAAO,eAAe,UAAU,YAAY,UAAU,QAAQ;AACpE"}
@@ -1,5 +1,7 @@
1
- import { n as AuthorizeDecision, v as Operation, w as Sync } from "./make-DJ0Q1SSc.mjs";
2
1
  import { Duration, Effect, Layer } from "effect";
2
+ import { Diagnostic } from "foldkit-surface";
3
+ import { AuthorizeDecision } from "./make.js";
4
+ import { Operation, Sync } from "./sync.js";
3
5
  import { Journal } from "foldkit-durable/core";
4
6
  import { RemoteUnauthenticated } from "foldkit-remote";
5
7
  /** The sliver of a Durable Object the host uses: state for the journal to open with. */
@@ -59,6 +61,14 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never>
59
61
  * worker, miniflare); pass one in tests.
60
62
  */
61
63
  readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined;
64
+ /**
65
+ * Where each upgrade's diagnostics go, with its request: a `HostDefect`
66
+ * for every failure answered "Internal error" (making the socket pair,
67
+ * the resolver, the journal, the exchange) and the rest `documentHost`
68
+ * reports. The reporter in the Effect context when not given, by default
69
+ * the log.
70
+ */
71
+ readonly diagnostics?: ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>) | undefined;
62
72
  }
63
73
  /**
64
74
  * What the resolver needs, from the environment: required exactly when it
@@ -87,4 +97,4 @@ export interface AcceptingWebSocket extends WebSocket {
87
97
  export declare const defineDocumentHost: <Message, Shared, Principal, Env, RP = never>(Base: new (ctx: DocumentHostContext, env: Env) => object, config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>) => new (ctx: DocumentHostContext, env: Env) => {
88
98
  fetch(request: Request): Promise<Response>;
89
99
  };
90
- //# sourceMappingURL=do.d.mts.map
100
+ //# sourceMappingURL=do.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do.d.ts","names":[],"sources":["../src/do.ts"],"mappings":";;;;;;;iBA2CiB;WACN;;;iBAIM,mBAAmB,SAAS,QAAQ,WAAW,KAAK;;WAE1D,MAAM,KAAK,SAAS;;;;;;;;WAQpB,cACP,KAAK,qBACL,KAAK,QACF,QAAQ,QAAQ,WAAW,QAAQ,WAAW;;;;;;;;WAQ1C,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,WAAW,uBAAuB;;;;;;;WAO5C,WAEH,KAAK,KACL,SAAS,QAAQ,WAAW,QAAQ,WAAW,eAC5C,OAAO;;;;;;;;;;WAWP;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,UAAU,WAAW,cAAc,OAAO;;;;;WAK1C,UAEH,WAAW,WACX,WAAW,cACR,oBAAoB,OAAO,OAAO;;;;;;WAOlC,wBAAwB,QAAQ,WAAW,QAAQ;;;;;;;;WAQnD,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;;;;;;;YAUhD,kBAAkB,KAAK,OAAO;WAC3B;;WACA,QAAQ,KAAK,QAAQ,MAAM,MAAM;;;;;;iBAM/B,2BAA2B;EAC1C;;;;;;;;qBAuCW,qBAAsB,SAAS,QAAQ,WAAW,KAAK,YAAU,WACjE,KAAK,qBAAqB,KAAK,gBAAc,QAChD,mBAAmB,SAAS,QAAQ,WAAW,KAAK,MAAM,kBAAkB,KAAK,aACnF,KAAK,qBAAqB,KAAK;EAAU,MAAM,SAAS,UAAU,QAAQ"}
@@ -1,6 +1,8 @@
1
- import { u as workerSocket } from "./transport-BZ6utYmB.mjs";
2
- import { n as documentHost, s as checkRevalidate } from "./journal-D5h-jqXE.mjs";
3
- import { Result } from "effect";
1
+ import { Cause, Effect, Result } from "effect";
2
+ import { documentHost } from "./journal.js";
3
+ import { checkRevalidate } from "./revalidate.js";
4
+ import { hostDefect, reportTo } from "./diagnostics.js";
5
+ import { workerSocket } from "./transport.js";
4
6
  // src/do.ts
5
7
  /**
6
8
  * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare
@@ -72,17 +74,22 @@ const defineDocumentHost = (Base, config) => {
72
74
  revalidate: config.revalidate,
73
75
  settle: settle === void 0 ? void 0 : (journal) => settle(env, journal),
74
76
  opens: config.opens,
75
- admit: config.admit
77
+ admit: config.admit,
78
+ diagnostics: config.diagnostics
76
79
  });
77
80
  }
78
81
  async fetch(request) {
79
82
  if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return Response.json({ error: "not found" }, { status: 404 });
83
+ const broke = async (error) => {
84
+ const { diagnostics } = config;
85
+ await Effect.runPromise(reportTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request), hostDefect("Upgrade", Cause.die(error))));
86
+ return Response.json({ error: "Internal error" }, { status: 500 });
87
+ };
80
88
  let pair;
81
89
  try {
82
90
  pair = (config.pair ?? defaultPair)();
83
91
  } catch (error) {
84
- console.error("[foldkit-sync] serving an upgrade broke:", error);
85
- return Response.json({ error: "Internal error" }, { status: 500 });
92
+ return broke(error);
86
93
  }
87
94
  const [client, server] = pair;
88
95
  const answered = await this.host(request);
@@ -99,13 +106,12 @@ const defineDocumentHost = (Base, config) => {
99
106
  webSocket: client
100
107
  });
101
108
  } catch (error) {
102
- console.error("[foldkit-sync] serving an upgrade broke:", error);
103
109
  abandon();
104
- return Response.json({ error: "Internal error" }, { status: 500 });
110
+ return broke(error);
105
111
  }
106
112
  }
107
113
  };
108
114
  };
109
115
  export { defineDocumentHost };
110
116
 
111
- //# sourceMappingURL=do.mjs.map
117
+ //# sourceMappingURL=do.js.map
package/dist/do.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do.js","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 =>\n * Effect.succeed({ 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 { Cause, type Duration, Effect, type Layer, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Diagnostic } from 'foldkit-surface'\nimport type { Journal } from 'foldkit-durable/core'\nimport {\n documentHost,\n type Accepted,\n type DocumentHostOptions,\n type DocumentHostOptionsLayer,\n} from './journal.js'\nimport { checkRevalidate } from './revalidate.js'\nimport { hostDefect, reportTo } from './diagnostics.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, RP = never> {\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 /**\n * Who is opening this socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`\n * makes one) to refuse it: a 401 carrying its message. A defect is a 500\n * that says nothing of it. What it needs (a session store) comes from\n * `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\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 /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket\n * serves the principal it opened with until it closes, a revoked session\n * included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\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 * Where each upgrade's diagnostics go, with its request: a `HostDefect`\n * for every failure answered \"Internal error\" (making the socket pair,\n * the resolver, the journal, the exchange) and the rest `documentHost`\n * reports. The reporter in the Effect context when not given, by default\n * the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n}\n\n/**\n * What the resolver needs, from the environment: required exactly when it\n * needs something. Built per upgrade and kept until the socket closes, since\n * `revalidate` asks the resolver again while it is open; an upgrade that is\n * refused closes it at once.\n */\nexport type DocumentHostLayer<Env, RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: (env: Env) => Layer.Layer<RP> }\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\n/**\n * Closes a socket with `code`, and `reason` when the platform takes it: a\n * reason past 123 bytes, or a socket already gone, still closes or is closed.\n */\nconst closeWith = (socket: WebSocket, code: number, reason: string): void => {\n try {\n socket.close(code, reason)\n } catch {\n try {\n socket.close(code)\n } catch {\n // Already closed.\n }\n }\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 })\n | 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 refused principal is a 401; a\n * resolver that breaks, or a journal that never opened, a 500 that says\n * nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env, RP = never>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>,\n): new (ctx: DocumentHostContext, env: Env) => { fetch(request: Request): Promise<Response> } => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n let ready: Promise<Journal<Operation, Shared, Principal, Operation>> | undefined\n const { layer, settle } = config\n this.host = documentHost<Message, Shared, Principal, RP>({\n sync: config.sync,\n // Opened on the first upgrade a principal passes, so probes never\n // provision storage; a failed open is tried again on the next.\n journal: () =>\n (ready ??= config.openJournal(ctx, env)).catch((error: unknown) => {\n ready = undefined\n throw error\n }),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle: settle === undefined ? undefined : journal => settle(env, journal),\n opens: config.opens,\n admit: config.admit,\n diagnostics: config.diagnostics,\n // `DocumentHostLayer` already tied `layer` to `RP` on the config; the\n // conditional cannot be resolved for an `RP` still generic here.\n } as DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>)\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 // The replica learns nothing of it; whoever runs the host must.\n const broke = async (error: unknown): Promise<Response> => {\n const { diagnostics } = config\n await Effect.runPromise(\n reportTo(\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request),\n hostDefect('Upgrade', Cause.die(error)),\n ),\n )\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n // Made first: a runtime without WebSocketPair is a 500 that resolves no one.\n let pair: readonly [client: WebSocket, server: AcceptingWebSocket]\n try {\n pair = (config.pair ?? defaultPair)()\n } catch (error) {\n return broke(error)\n }\n const [client, server] = pair\n const answered = await this.host(request)\n if (Result.isFailure(answered)) return answered.failure\n const { serve, abandon } = answered.success\n try {\n server.accept()\n serve({\n ...workerSocket(server),\n closeWith: (code, reason) => closeWith(server, code, reason),\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 } catch (error) {\n abandon()\n return broke(error)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAM,aAAa,QAAmB,MAAc,WAAyB;CAC3E,IAAI;EACF,OAAO,MAAM,MAAM,MAAM;CAC3B,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,IAAI;EACnB,QAAQ,CAER;CACF;AACF;AAEA,MAAM,oBAA8E;CAClF,MAAM,QACJ,WAKA;CACF,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,OAAO,IAAI,MAAM;CACvB,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;;;AAQA,MAAa,sBACX,MACA,WAC+F;CAC/F,gBAAgB,OAAO,YAAY,oBAAoB;CACvD,OAAO,cAAc,KAAK;EACxB;EAEA,YAAY,KAA0B,KAAU;GAC9C,MAAM,KAAK,GAAG;GACd,IAAI;GACJ,MAAM,EAAE,OAAO,WAAW;GAC1B,KAAK,OAAO,aAA6C;IACvD,MAAM,OAAO;IAGb,gBACG,UAAU,OAAO,YAAY,KAAK,GAAG,EAAA,CAAG,OAAO,UAAmB;KACjE,QAAQ,KAAA;KACR,MAAM;IACR,CAAC;IACH,mBAAkB,YAAW,OAAO,iBAAiB,SAAS,GAAG;IACjE,OAAO,UAAU,KAAA,IAAY,KAAA,UAAkB,MAAM,GAAG;IACxD,YAAY,OAAO;IACnB,QAAQ,WAAW,KAAA,IAAY,KAAA,KAAY,YAAW,OAAO,KAAK,OAAO;IACzE,OAAO,OAAO;IACd,OAAO,OAAO;IACd,aAAa,OAAO;GAGtB,CAAuF;EACzF;EAEA,MAAM,MAAM,SAAqC;GAC/C,IAAI,QAAQ,QAAQ,IAAI,SAAS,CAAC,EAAE,YAAY,MAAM,aACpD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;GAE9D,MAAM,QAAQ,OAAO,UAAsC;IACzD,MAAM,EAAE,gBAAgB;IACxB,MAAM,OAAO,WACX,SACE,gBAAgB,KAAA,IAAY,KAAA,KAAY,eAAc,YAAY,YAAY,OAAO,GACrF,WAAW,WAAW,MAAM,IAAI,KAAK,CAAC,CACxC,CACF;IACA,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;GACnE;GAEA,IAAI;GACJ,IAAI;IACF,QAAQ,OAAO,QAAQ,YAAA,CAAa;GACtC,SAAS,OAAO;IACd,OAAO,MAAM,KAAK;GACpB;GACA,MAAM,CAAC,QAAQ,UAAU;GACzB,MAAM,WAAW,MAAM,KAAK,KAAK,OAAO;GACxC,IAAI,OAAO,UAAU,QAAQ,GAAG,OAAO,SAAS;GAChD,MAAM,EAAE,OAAO,YAAY,SAAS;GACpC,IAAI;IACF,OAAO,OAAO;IACd,MAAM;KACJ,GAAG,aAAa,MAAM;KACtB,YAAY,MAAM,WAAW,UAAU,QAAQ,MAAM,MAAM;IAC7D,CAAC;IACD,OAAO,IAAI,SAAS,MAAM;KACxB,QAAQ;KAGR,WAAW;IACb,CAAiB;GACnB,SAAS,OAAO;IACd,QAAQ;IACR,OAAO,MAAM,KAAK;GACpB;EACF;CACF;AACF"}
@@ -116,4 +116,4 @@ export declare const EditableEntity: {
116
116
  };
117
117
  export type EditableEntity<E extends EntityFields, Ms extends ReadonlyArray<Member<E>>> = ReturnType<typeof make<E, Ms>>;
118
118
  export {};
119
- //# sourceMappingURL=entity.d.mts.map
119
+ //# sourceMappingURL=entity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity.d.ts","names":[],"sources":["../src/entity.ts"],"mappings":";;qBAkBa,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,KAAG,QACrE,GAAC;WACW,SAAS;;;;;;;;;;;;;IAoEzB,SAAO,OAAA,OAAA,OAAA,MAAA,OAAA,GAAA;;IAEP,IAAE,OAAA,YAAA,OAAA;IACF,IAAE,OAAA,YAAA,OAAA;;;;;;;IAGQ,SAAO,OAAA;;;EAED,UAAA;aACP;aACA;aACA;;IACF;IAAqB;MAAM;MAAuB;;;;EAIlD,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;;;;;;EAS7B,WAAA,UAAA,cAAa,SAAA,GAAA,cAAM,MACvB,cAAa,SAAA,GAAA,cAAM,oBAExB,cAAc,SAAQ,SAAA,GAAA;;EAiBd,UAAA,SAAA,cAAc,OAAO,GAAC,iBAC9B;aAAyB,IAAI,KAAK;aAAa,QAAM;;;;;;EAOvB,WAAA,KAAA,MAAA,GAAA,aAAA,QAAA,eAAA,OAAO,GAAC;;EAKzB,SAAA,OAAA,cAAa,SAAA,GAAA,cAAM,KAAO,KAAK,IAAE,QAAA,eAAc,OAAO,OAAM,SAAA,GAAA;EA7F3C,OAAA,MAAA,SAAA,GAAA,aAAA;;;qBAuGxB;;;YACD,eACV,UAAU,cACV,WAAW,cAAc,OAAO,OAC9B,kBAAkB,KAAK,GAAG"}
@@ -139,4 +139,4 @@ const make = (entity, options) => {
139
139
  const EditableEntity = { make };
140
140
  export { Author, EditableEntity };
141
141
 
142
- //# sourceMappingURL=entity.mjs.map
142
+ //# sourceMappingURL=entity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity.js","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,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,KAAI,WACV,OAAO,OAAO;EAAE;EAAI,QAAQ,OAAO,QAAQ,MAAM;EAAG,OAAO,SAAS,MAAM;CAAE,CAAC,CAC/E,CACF;CACA,MAAM,OAAO,OAAO,MAClB,QAAQ,KAAI,WACV,OAAO,OAAO;EACZ;EACA,QAAQ,OAAO,QAAQ,MAAM;EAC7B,OAAO,SAAS,MAAM;EACtB,IAAI,OAAO,iBAAiB,OAAO,MAAM;EACzC,IAAI,OAAO,iBAAiB,MAAM;CACpC,CAAC,CACH,CACF;;CAGA,MAAM,WAAW,UAA+B;EAC9C,MAAM,wBAAQ,IAAI,IAA2B;EAC7C,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,MAAM,MAAM,IAAI,KAAK,EAAE,qBAAK,IAAI,IAAa;GACnD,IAAI,IAAI,KAAK,QAAQ,IAAI;GACzB,MAAM,IAAI,KAAK,IAAI,GAAG;EACxB;EACA,OAAO;CACT;CACA,MAAM,YAAY,GAAiD,MACjE,MAAM,OAAO,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE;;CAG7C,MAAM,WAAW,MAAY,aAAqB,OAAO,OAAO,KAAK,KAAI,OAAM,MAAM,QAAQ;;CAG7F,MAAM,QAAQ,MAAY,YACxB,OAAO,MAAM,KAAK,IAAI;EACpB,cAAc;EACd,cAAc,OAAO,OAAO,KAAK,KAAI,OAAM,GAAG,YAAY,OAAO;CACnE,CAAC;CAEH,OAAO;;EAEL;EACA;;EAEA,QAAQ,OAAO,SAAS,OAAO;;EAE/B;;EAEA;;EAEA,QAAQ;GACN,SAAS,OAAO,MAAM,MAAM;;GAE5B,IAAI,OAAO,YAAY,OAAO,MAAM;GACpC,IAAI,OAAO,YAAY,MAAM;EAC/B;;EAEA,UAAU,EAAE,SAAS,OAAO,OAAO;;EAEnC,UAAU,YAIH;GAAE,IAAI,OAAO;GAAU,IAAI;IAAE,OAAO,OAAO;IAAS,SAAS,OAAO;GAAU;EAAE;;EAGvF,QACE,OACA,SACA,IACA,OACwB;GACxB,IAAI,QAAQ,WAAW,GAAG,OAAO;GACjC,MAAM,QAAQ,QAAQ,KAAI,YAAW;IAAE,GAAG;IAAQ;IAAI;GAAG,EAAU;GACnE,OAAO,CAAC,GAAG,MAAM,QAAO,SAAQ,CAAC,MAAM,MAAK,SAAQ,SAAS,MAAM,IAAI,CAAC,CAAC,GAAG,GAAG,KAAK;EACtF;;EAGA,SAAS,OAA4B,YACnC,MAAM,MAAK,SAAQ,QAAQ,MAAM,OAAO,CAAC,IACrC,MAAM,QAAO,SAAQ,CAAC,QAAQ,MAAM,OAAO,CAAC,IAC5C;;EAGN,eAAe,OAA4B,YACzC,MAAM,MAAK,SAAQ,QAAQ,MAAM,OAAO,CAAC;;;;;;EAO3C,WACE,UACA,MACA,YACkC;GAClC,MAAM,SAAS,QAAQ,QAAQ;GAC/B,OAAO,KAAK,SAAQ,SAAQ;IAC1B,MAAM,QAAQ,OAAO,IAAI,KAAK,EAAE,CAAC,EAAE,IAAI,KAAK,MAAM;IAClD,IAAI,UAAU,KAAA,KAAa,CAAC,KAAK,OAAO,OAAO,GAAG,OAAO,CAAC;IAC1D,OAAO,OAAO,MAAM,KAAK,IAAI;KAC3B,cAAc,CAAC;KACf,SAAQ,OACN,GAAG,YAAY,WAAW,CAAC,MAAM,OAAO,KAAK,OAAO,MAAM,KAAK,IAC3D,CAAC;MAAE,MAAM;MAAO,IAAI,OAAO,KAAK,EAAE;KAAE,CAAC,IACrC,CAAC;IACT,CAAC;GACH,CAAC;EACH;;EAGA,UACE,YAEA,QAAQ,KAAK,EAAE,IAAI,KAAK,cAAc;GAAE,IAAI;GAAK;EAAO,EAAE;;;;;EAM5D,WAAW,KAAU,YAElB;GAAE,IAAI,IAAI;GAAI;GAAQ,OAAO,IAAI;EAAQ;;EAG5C,SAAS,OAA4B,KAAc,WACjD,OAAO,gBACL,MAAM,MAAK,SAAQ,MAAM,OAAO,KAAK,IAAI,GAAG,KAAK,KAAK,WAAW,MAAM,CACzE;EAEF;CACF;AACF;;AAGA,MAAa,iBAAiB,EAAE,KAAK"}
@@ -0,0 +1,91 @@
1
+ import { Schema } from "effect";
2
+ declare const StorageError_base: Schema.Class<StorageError, Schema.TaggedStruct<"StorageError", {
3
+ readonly message: Schema.String;
4
+ readonly cause: Schema.optional<Schema.Unknown>;
5
+ }>, import("effect/Cause").YieldableError>;
6
+ /** The persisted storage could not be read or written. */
7
+ export declare class StorageError extends StorageError_base {}
8
+ declare const UnsupportedClockVersionError_base: Schema.Class<UnsupportedClockVersionError, Schema.TaggedStruct<"UnsupportedClockVersionError", {
9
+ readonly schemaVersion: Schema.NullOr<Schema.Number>;
10
+ readonly message: Schema.String;
11
+ }>, import("effect/Cause").YieldableError>;
12
+ /** The stored clock state targets a schema version this build does not support. */
13
+ export declare class UnsupportedClockVersionError extends UnsupportedClockVersionError_base {}
14
+ declare const WrongReplicaStorageError_base: Schema.Class<WrongReplicaStorageError, Schema.TaggedStruct<"WrongReplicaStorageError", {
15
+ readonly documentId: Schema.String;
16
+ readonly replicaId: Schema.String;
17
+ readonly message: Schema.String;
18
+ }>, import("effect/Cause").YieldableError>;
19
+ /** The storage holds a different replica's state. */
20
+ export declare class WrongReplicaStorageError extends WrongReplicaStorageError_base {}
21
+ declare const InvalidReplicaHistoryError_base: Schema.Class<InvalidReplicaHistoryError, Schema.TaggedStruct<"InvalidReplicaHistoryError", {
22
+ readonly message: Schema.String;
23
+ readonly cause: Schema.optional<Schema.Unknown>;
24
+ }>, import("effect/Cause").YieldableError>;
25
+ /** The persisted replica history is internally inconsistent. */
26
+ export declare class InvalidReplicaHistoryError extends InvalidReplicaHistoryError_base {}
27
+ declare const InvalidExchangeError_base: Schema.Class<InvalidExchangeError, Schema.TaggedStruct<"InvalidExchangeError", {
28
+ readonly message: Schema.String;
29
+ readonly cause: Schema.optional<Schema.Unknown>;
30
+ }>, import("effect/Cause").YieldableError>;
31
+ /** The server's exchange response did not match the protocol schema. */
32
+ export declare class InvalidExchangeError extends InvalidExchangeError_base {}
33
+ declare const InvalidOutboxError_base: Schema.Class<InvalidOutboxError, Schema.TaggedStruct<"InvalidOutboxError", {
34
+ readonly message: Schema.String;
35
+ }>, import("effect/Cause").YieldableError>;
36
+ /** A persisted pending operation could not have been produced by this replica. */
37
+ export declare class InvalidOutboxError extends InvalidOutboxError_base {}
38
+ declare const CheckpointRegressionError_base: Schema.Class<CheckpointRegressionError, Schema.TaggedStruct<"CheckpointRegressionError", {
39
+ readonly cursor: Schema.Number;
40
+ readonly checkpointCursor: Schema.Number;
41
+ readonly message: Schema.String;
42
+ }>, import("effect/Cause").YieldableError>;
43
+ /** The server sent a checkpoint older than the replica's cursor. */
44
+ export declare class CheckpointRegressionError extends CheckpointRegressionError_base {}
45
+ declare const CommittedOrderError_base: Schema.Class<CommittedOrderError, Schema.TaggedStruct<"CommittedOrderError", {
46
+ readonly expected: Schema.Number;
47
+ readonly actual: Schema.Number;
48
+ readonly message: Schema.String;
49
+ }>, import("effect/Cause").YieldableError>;
50
+ /** Committed operations were not contiguous from the replica's cursor. */
51
+ export declare class CommittedOrderError extends CommittedOrderError_base {}
52
+ declare const ForeignRejectionError_base: Schema.Class<ForeignRejectionError, Schema.TaggedStruct<"ForeignRejectionError", {
53
+ readonly opId: Schema.String;
54
+ readonly message: Schema.String;
55
+ }>, import("effect/Cause").YieldableError>;
56
+ /** The server rejected an operation the replica never sent. */
57
+ export declare class ForeignRejectionError extends ForeignRejectionError_base {}
58
+ declare const ForeignAcknowledgementError_base: Schema.Class<ForeignAcknowledgementError, Schema.TaggedStruct<"ForeignAcknowledgementError", {
59
+ readonly opId: Schema.String;
60
+ readonly message: Schema.String;
61
+ }>, import("effect/Cause").YieldableError>;
62
+ /**
63
+ * The server answered an operation this request never sent, or both
64
+ * acknowledged and rejected it. Acting on either would let a faulty or hostile
65
+ * server delete local work.
66
+ */
67
+ export declare class ForeignAcknowledgementError extends ForeignAcknowledgementError_base {}
68
+ declare const ReplicaClosedError_base: Schema.Class<ReplicaClosedError, Schema.TaggedStruct<"ReplicaClosedError", {
69
+ readonly message: Schema.String;
70
+ }>, import("effect/Cause").YieldableError>;
71
+ /** The replica was closed while work was still being submitted. */
72
+ export declare class ReplicaClosedError extends ReplicaClosedError_base {}
73
+ declare const UnsupportedReplicaVersionError_base: Schema.Class<UnsupportedReplicaVersionError, Schema.TaggedStruct<"UnsupportedReplicaVersionError", {
74
+ readonly protocolVersion: Schema.NullOr<Schema.Number>;
75
+ readonly schemaVersion: Schema.NullOr<Schema.Number>;
76
+ readonly message: Schema.String;
77
+ }>, import("effect/Cause").YieldableError>;
78
+ /** The stored replica state targets a protocol or schema version this build does not support. */
79
+ export declare class UnsupportedReplicaVersionError extends UnsupportedReplicaVersionError_base {}
80
+ declare const ReplayError_base: Schema.Class<ReplayError, Schema.TaggedStruct<"ReplayError", {
81
+ readonly message: Schema.String;
82
+ readonly cause: Schema.optional<Schema.Unknown>;
83
+ }>, import("effect/Cause").YieldableError>;
84
+ /**
85
+ * `replay` threw for a submitted Message, so it could never be applied here or
86
+ * on any other replica; nothing was written.
87
+ */
88
+ export declare class ReplayError extends ReplayError_base {}
89
+ export type ReplicaError = StorageError | ReplayError | WrongReplicaStorageError | InvalidReplicaHistoryError | InvalidExchangeError | UnsupportedReplicaVersionError | InvalidOutboxError | CheckpointRegressionError | CommittedOrderError | ForeignRejectionError | ForeignAcknowledgementError | ReplicaClosedError;
90
+ export {};
91
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;;;;;qBAGa,qBAAqB;;;;;;qBAMrB,qCAAqC;;;;;;;qBASrC,iCAAiC;;;;;;qBAUjC,mCAAmC;;;;;;qBASnC,6BAA6B;;;;;qBAS7B,2BAA2B;;;;;;;qBAQ3B,kCAAkC;;;;;;;qBAUlC,4BAA4B;;;;;;qBAU5B,8BAA8B;;;;;;;;;;qBAa9B,oCAAoC;;;;;qBASpC,2BAA2B;;;;;;;qBAQ3B,uCAAuC;;;;;;;;;qBAavC,oBAAoB;YAKrB,eACR,eACA,cACA,2BACA,6BACA,uBACA,iCACA,qBACA,4BACA,sBACA,wBACA,8BACA"}