@collective-intelligence/external-apps-client-sdk-react 0.11.0 → 0.12.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/AGENTS.md CHANGED
@@ -1,34 +1,42 @@
1
1
  # `@collective-intelligence/external-apps-client-sdk-react`: agent guide
2
2
 
3
3
  React bindings of Collective Intelligence (CI) external applications: the
4
- provider, Embedded Sign-In components, entity hooks with Optimistic Writes,
5
- declared entity views, realtime hooks, and the Effect bridge for XState
6
- machines. The package `README.md`
7
- holds the full API.
4
+ provider, Embedded Sign-In components, entity hooks, declared entity views,
5
+ realtime hooks, the Effect bridge for XState machines, and the record layer
6
+ (Record Collections on TanStack DB). The package `README.md` holds the full
7
+ API.
8
8
 
9
9
  ## Rules
10
10
 
11
11
  - Import entity hooks and views from `/resources`, the Effect bridge
12
- (`fromEffect`, `EffectRuntimeProvider`, `QueryCache`) from `/effect`, and
13
- the realtime bindings (`RealtimeProvider`, `useRealtimeTopic`,
14
- `useRealtimeClient`) from `/realtime`. The root holds them too, but it
15
- bundles the sign-in, agent prompt and entity UI with them.
12
+ (`fromEffect`, `EffectRuntimeProvider`, `QueryCache`) from `/effect`, the
13
+ realtime bindings (`RealtimeProvider`, `useRealtimeTopic`,
14
+ `useRealtimeClient`) from `/realtime`, and the record layer
15
+ (`RecordCollections`, `RecordWrites`, `useRecordRuntime`, `entityTopic`,
16
+ `entityWriteTarget`, `seedRecords`, `RecordSeedBoundary`, `fromTransaction`,
17
+ `fromLiveQuery`)
18
+ from `/records`. The root holds all but `/records` too, but it bundles the
19
+ sign-in, agent prompt and entity UI with them.
16
20
  - Install the peers once in the app: `react`, `react-dom`,
17
- `@tanstack/react-query`, `xstate`, `effect` (`^4.1.0`) and
18
- `@collective-intelligence/ui-react`.
19
- - Keep user-scoped reads in TanStack Query: the entity hooks, or `useQuery` on
20
- the keys that `QueryCache` writes. Only reads with the app's own credential
21
+ `@tanstack/react-query`, `xstate`, `effect` (`^4.1.0`),
22
+ `@collective-intelligence/ui-react`, and the TanStack DB peers with the
23
+ exact versions of the package's `peerDependencies`.
24
+ - Keep CI records that a view writes or follows in a Record Collection, and
25
+ write them with the entity hooks, or with `RecordWrites` and
26
+ `entityWriteTarget(contract)`. For a write that the SDK cannot express,
27
+ file an SDK gap; write no optimistic value, record cache or write queue in
28
+ the app.
29
+ - Keep user-scoped reads in TanStack Query or a Record Collection: the entity
30
+ hooks, `useQuery` on the keys that `QueryCache` writes, or a live query.
31
+ Only reads with the app's own credential
21
32
  go into the Next.js server cache (`cacheCiRead` of the server SDK).
22
33
  - To share one cache, pass the app's QueryClient to
23
34
  `CollectiveIntelligenceProvider` as `queryClient`.
24
35
  - Run each side effect of a machine in a `fromEffect` actor. Keep remote data
25
36
  in `QueryCache`, never in machine context. After a write, refresh reads with
26
37
  `QueryCache` (`invalidate`, `setData`, `update`, `remove`); do not put the
27
- QueryClient in machine input. An optimistic write of one key uses
28
- `QueryCache.optimisticUpdate`; build its payload in a `write` function,
29
- which gets the confirmed value when CI gets the write, and give CI's answer
30
- to `confirm`. Its edit must give the same value for a value that already
31
- holds it, as a fetch can end under it. A write of several keys calls `cancel` on
38
+ QueryClient in machine input. `QueryCache` has no optimistic write. A
39
+ write of several keys calls `cancel` on
32
40
  them before `update`, and `invalidate` when the write settles. A view
33
41
  renders: it calls no `fetch` and runs no Effect.
34
42
  - Give a single action of a view, such as a download or a share, an
@@ -39,8 +47,8 @@ holds the full API.
39
47
  member. Seed `queryClient`, then assert on its entries or on `calls`.
40
48
  - Show write failures with `onWriteFailed` on the provider, for example
41
49
  `ciWriteFailedToast()` of `@collective-intelligence/ui-react/ui`.
42
- - Give `RealtimeProvider` an `onReset` that refetches every realtime-driven
43
- query.
50
+ - Give `RealtimeProvider` an `onResync` that reloads every realtime-driven
51
+ query on every call.
44
52
  - For a sign-in form in the app, give `CollectiveIntelligenceLoginProvider`
45
53
  the auth of `createServerSessionAuth` and render `<SignInCard>`, or the
46
54
  `SignIn.*` parts, or read `useSignIn()` inside `SignIn.Root`. Do not build
@@ -48,6 +56,11 @@ holds the full API.
48
56
 
49
57
  ## Index
50
58
 
59
+ - [docs/record-collections.md](docs/record-collections.md): read when a
60
+ view or machine reads or writes CI records, or you choose between a
61
+ Realtime Record Collection, a Query Record Collection and a plain query.
62
+ - [docs/tanstack-skills.md](docs/tanstack-skills.md): read before you load
63
+ TanStack DB skills or follow the repository `tanstack-query` skill.
51
64
  - [docs/effect.md](docs/effect.md): read when you write an XState machine
52
65
  that calls CI, or connect Effect code to the QueryClient.
53
66
  - [docs/realtime.md](docs/realtime.md): read when a view must follow changes
@@ -55,11 +68,20 @@ holds the full API.
55
68
  - [docs/sign-in.md](docs/sign-in.md): read when the app shows its own
56
69
  sign-in or registration form.
57
70
  - [docs/errors.md](docs/errors.md): read when you handle a failed entity read
58
- or write, or an Optimistic Write goes back.
71
+ or write, or a write rolls back.
59
72
  - [skills/client-sdk-react-move-to-effect/SKILL.md](skills/client-sdk-react-move-to-effect/SKILL.md):
60
73
  run when machines use `fromPromise`, `fromCallback` or observable actors, a
61
74
  view runs an Effect, or lint reports `ci-solution/effect-actors` or
62
75
  `ci-solution/no-run-in-view`.
76
+ - [skills/client-sdk-react-record-collections/SKILL.md](skills/client-sdk-react-record-collections/SKILL.md):
77
+ run when a view or machine reads CI records that it writes or follows, or
78
+ code imports `@tanstack/db` or `@tanstack/react-db`.
79
+ - [skills/client-sdk-react-move-to-record-collections/SKILL.md](skills/client-sdk-react-move-to-record-collections/SKILL.md):
80
+ run when the type-check fails on `optimisticUpdate`, `pending`,
81
+ `QueryCacheWriteValues` or `QueryCacheOptimisticOptions`, or code imports
82
+ an `optimistic-write` module.
83
+ - [skills/client-sdk-react-tanstack-db-ssr/SKILL.md](skills/client-sdk-react-tanstack-db-ssr/SKILL.md):
84
+ run when a page shows Record Collection rows on first load.
63
85
 
64
86
  ## Platform guide
65
87
 
package/README.md CHANGED
@@ -12,7 +12,12 @@ Install these required peer dependencies in the application: `react`, `react-dom
12
12
  depends on `@collective-intelligence/external-apps-client-sdk` as a normal dependency. The packed
13
13
  JavaScript bundles none of these packages, so the application holds one copy of each. The `./effect` entry
14
14
  holds the [Effect bridge](#effect-bridge) for XState machines. The `./realtime` entry holds the
15
- [realtime bindings](#realtime-topics) without the sign-in, agent prompt and entity UI.
15
+ [realtime bindings](#realtime-topics) without the sign-in, agent prompt and entity UI. The `./records`
16
+ entry holds the record layer: Record Collections on TanStack DB (`RecordCollections`,
17
+ `useRecordRuntime`, `entityTopic`), `RecordWrites` with `entityWriteTarget`, the server seed (`seedRecords`,
18
+ `getRequestClients` in its `react-server` build, `RecordSeedBoundary`) and the machine bridge
19
+ (`fromTransaction`, `fromLiveQuery`). It needs the TanStack DB peers at the exact versions of
20
+ `peerDependencies`; the packed `docs/record-collections.md` guide explains it.
16
21
 
17
22
  Configure the provider's `entitySource` once, alongside its existing Promise `client`. `EntitySource`
18
23
  exposes a stable `getSnapshot`, a `subscribe` function, and a typed `bind(contract)` function returning
@@ -51,10 +56,12 @@ and `resubmit`. Status distinguishes `conflict`, `rejected`, and `uncertain` fro
51
56
  one operation key. A new submit creates a new action; resubmit preserves the previous action exactly.
52
57
  Keep editable drafts in the form and use `submitted` for the retained action; a successful replay
53
58
  does not overwrite a newer draft. Same-record update/delete calls serialize across hook instances;
54
- different records and separate creates remain independent. Queued writes retain their original
55
- revisions. Form unmount does not cancel a dispatched write. Source transitions clear protected reads
56
- and reject stale queued actions before dispatch. Queries and mutations never automatically retry;
57
- there is no persistence, reload recovery, or automatic revision rebasing.
59
+ different records and separate creates remain independent. A queued write sends the revision that
60
+ the write before it confirmed (see [Record Writes](#record-writes)). Form unmount does not
61
+ cancel a dispatched write. Source transitions clear protected reads and reject stale queued actions
62
+ before dispatch. Queries never automatically retry; a write whose answer was lost is sent again with
63
+ its idempotency key. The provider keeps pending writes in an outbox per user and Organization and
64
+ sends them once after a reload; a sign-out drops them.
58
65
 
59
66
  Entity reads and writes run on the Effect Core of the client SDK, through the entity clients that
60
67
  the entity source binds. Their errors stay `ResourceResult` values: a read that fails gives
@@ -121,34 +128,47 @@ const auth = createServerSessionAuth({ basePath: "/api/auth" })
121
128
  `@collective-intelligence/ui-react/ui-extensions/labeled-field`, so the
122
129
  application installs `react-hook-form`, a required peer of `ui-react`.
123
130
 
124
- ## Optimistic Writes
125
-
126
- Entity writes are Optimistic Writes. The value is in the QueryClient cache, so every view that
127
- reads the record changes at once:
128
-
129
- - Before CI answers an update or a delete, the record view and each cached list page show the
130
- new value. A deleted record has `deletedAt` in its record view and leaves the list pages.
131
- - A create shows a pending row at the start of each cached first list page. Its `id` is the
132
- idempotency key and its `value` is the create input. CI's record replaces it.
133
- - To change the cache only when CI answers, pass `optimistic: false` in the target:
134
- `useEntityUpdate(contract, { id, optimistic: false })`, also for `useEntityDelete`.
135
- - Writes to one record run one at a time, in call order. Providers sharing a QueryClient share this ordering; separate QueryClients and record identities remain independent. An entity read of a record waits until
136
- the pending write of that record settles, and a list read waits for the pending writes of its
137
- resource. Thus a refetch after a realtime change or a Resync does not replace the shown value.
138
- - On success, the views show CI's record, and the write ends. Then each list view of the
139
- resource reads CI once more, because the write can change which records a list holds and in
140
- which order. The record view does not read again when it holds CI's record; after a failure,
141
- or when another fetch replaced it, it reads CI once more too. The write does not wait for
142
- these reads.
143
- - On a failure or an interruption, a view goes back to its value from before the write, but only
144
- when it still shows the write's value. In a list page, only the write's own row changes, so
145
- the rows of pending writes to other records stay. A read outside the entity hooks, for example
146
- an app `fetchQuery` on an entity key, does not wait for a write; the view then keeps that
147
- newer value. The read after the write shows CI's value in each case.
131
+ ## Record Writes
132
+
133
+ Entity writes are Record Collection transactions. `useEntityCreate`, `useEntityUpdate` and
134
+ `useEntityDelete` send each write through `RecordWrites` of `./records`, as one TanStack DB
135
+ transaction over every open Record Collection of the signed-in identity that shows the
136
+ contract's records, so each shows the write at once and rolls back only a refused write:
137
+
138
+ - Before CI answers, the app's Realtime Record Collections of an `entityTopic` of the contract
139
+ show the new value (a create when its value matches the topic's filter), Query Record
140
+ Collections opened with `target: entityWriteTarget(contract)` show updates and deletes of the
141
+ rows they hold, and the record's own Record Collection shows every write. A delete hides the
142
+ row. A create gives its record a client id (UUIDv7), so the optimistic row keeps its key when
143
+ CI confirms it. A store that assigns its own ids (a Remote-first CI schema, or an app store
144
+ resource that has not opted in to client ids, such as a server SDK Drizzle resource without
145
+ `entities.clientIdField`) refuses it with `details.reason: "client_id_not_supported"`;
146
+ the create is then sent once more without the id, and the row takes the store's id when it
147
+ answers; updates and deletes queued behind the create go to the store's id. A client id that
148
+ a record holds answers `conflict` (`details.reason: "id_taken"`).
149
+ - An update or a delete sends the revision of the app's collection that holds the row, a
150
+ Realtime Record Collection first. When no app collection holds it, the record's own
151
+ collection starts from the record that the form, the record view or a list page holds, and
152
+ reads CI only when none holds it. A Query Record Collection, such as the record's own, follows
153
+ no Change Hint, so when the edited revision is not the one it holds it reads CI again before
154
+ the edit counts as a conflict.
155
+ - Writes to one record run one at a time, in call order, also across bundled SDK copies. A
156
+ queued write sends the revision that the write before it confirmed. A write with no pending
157
+ write before it and an edited revision that the record no longer holds is a `conflict`, and is
158
+ not sent.
159
+ - A write whose answer was lost is sent again with the same idempotency key, for up to 60
160
+ seconds; the Write Receipt makes CI apply it once. Its outcome is `uncertain` only after that.
161
+ - CI's confirmed row is in each of those collections before the write settles, so no revert
162
+ shows, whether the Change Hint arrives before CI's answer or after it. Then the entity reads of
163
+ the resource read CI once more; a record view takes CI's record without a read.
164
+ - A Business Logic Machine or a flow writes without the hooks through `RecordWrites` (or
165
+ `fromTransaction`) with `entityWriteTarget(contract)`, `RecordId` and `IdempotencyKey` of
166
+ `./records`, on its own Record Collection; the write behaves as a hook's.
167
+ - `optimistic: false` in the target is kept for compatibility: every write shows at once.
148
168
 
149
169
  `onWriteFailed` on `CollectiveIntelligenceProvider` or `CollectiveIntelligenceLoginProvider`
150
170
  gets a `WriteFailed` for each entity write that CI refuses or that does not reach CI, after the
151
- views went back. `error` is a `CiError` (CI refused the write) or a `CiTransportError` (the
171
+ Record Collection rolled the write back. `error` is a `CiError` (CI refused the write) or a `CiTransportError` (the
152
172
  request did not reach CI, or its answer was lost); `operation` is `create`, `update` or
153
173
  `delete`; `label` is the resource id (`contract.id`). It is not called for an interruption, or
154
174
  when the entity source changed during the write. The provider calls the `onWriteFailed` of the
@@ -265,26 +285,28 @@ without resubscribing. It receives the changes of the topic in batches: one
265
285
  delivery per tab, 250 to 1000 ms after the first pending change, with the
266
286
  latest change of each record.
267
287
 
268
- Pass `onReset` and refetch every realtime-driven query in it. The client calls
269
- it with a reason: `"gap"` when the server cannot replay a gap, `"server"` at a
270
- delete the server cannot name, and `"initial"` after a stream opens without a
271
- last event id unless the server confirms with `resumed` that it replays the
272
- changes since the page started. A current server confirms it only when it
273
- can show that nothing is missed (the client SDK README lists the first opens
274
- that still resync), so most page loads need no refetch. The page
275
- starts at `startedAt`, by default `performance.timeOrigin`, which also covers
276
- a server render of the navigation; a page that shows cached data read
277
- earlier passes `performance.timeOrigin - ageMs`, with `ageMs` the age of that
278
- data when the server sent it. Without `onReset` the client cannot recover
279
- from such a gap, so a change can be lost. The client
280
- calls `onAccessChanged` when the user's access changes, and `onRefused` once
281
- when the server refuses the realtime link with 401 or 403 and the connection
282
- stops. They stay callbacks of the application; the client calls the ones of the latest render, also when a
283
- render adds or removes one. Only a client with `onReset` resyncs, so a render
284
- that adds or removes `onReset` replaces the client and its stream. The new
285
- stream opens without a last event id and asks for the changes since
286
- `startedAt`, so with `onReset` it resyncs once only when the server does not
287
- confirm that replay.
288
+ Pass `onResync` and reload every realtime-driven query in it. The client
289
+ calls it once per delivery that holds a Resync, with
290
+ `{ reason, reasons, generation, accessChanged }`. `reasons` lists the reasons
291
+ of the delivery's `resync` frames: `"gap"` when the server cannot replay a
292
+ gap, `"access"` when the user's access may have changed, `"server"` at a
293
+ delete the server cannot name, and `"first-open"` when a stream opens at no
294
+ position the server can replay from. With `accessChanged` true, also check
295
+ the session. Every call means reload, also for a generation seen before. A
296
+ first open asks for the changes since the page started at `startedAt`, by
297
+ default `performance.timeOrigin`, which also covers a server render of the
298
+ navigation; a page that shows cached data read earlier passes
299
+ `performance.timeOrigin - ageMs`, with `ageMs` the age of that data when the
300
+ server sent it. When the server replays them it sends `caught-up` and no
301
+ Resync, so most page loads need no reload. Without `onResync` the client
302
+ cannot recover from a gap, so a change can be lost. The client calls
303
+ `onRefused` once when the server refuses the realtime link with 401 or 403
304
+ and the connection stops. They stay callbacks of the application; the client
305
+ calls the ones of the latest render, also when a render adds or removes one.
306
+ Only a client with `onResync` resyncs, so a render that adds or removes
307
+ `onResync` replaces the client and its stream. The new stream opens without
308
+ a last event id and asks for the changes since `startedAt`, so with
309
+ `onResync` it reloads once only when the server cannot replay them.
288
310
 
289
311
  ```tsx
290
312
  const AppRealtime = ({ children }: { children: ReactNode }) => {
@@ -292,8 +314,7 @@ const AppRealtime = ({ children }: { children: ReactNode }) => {
292
314
  return (
293
315
  <RealtimeProvider
294
316
  ticketUrl="/api/realtime/ticket"
295
- onReset={() => queryClient.invalidateQueries()}
296
- onAccessChanged={() => queryClient.invalidateQueries()}
317
+ onResync={() => queryClient.invalidateQueries()}
297
318
  >
298
319
  {children}
299
320
  </RealtimeProvider>
@@ -314,8 +335,7 @@ For the entity hooks, `useEntityChanges(contract)` of `./resources` gives the
314
335
  `onChanges` that refreshes their reads. The record entry of a changed id
315
336
  reads CI again, unless it already holds the revision of the change, such as
316
337
  the record that the tab's own write stored. Every list of the resource reads
317
- CI again, because a change can change which records a list holds. Each read
318
- waits for the pending writes of its records.
338
+ CI again, because a change can change which records a list holds.
319
339
 
320
340
  ```tsx
321
341
  const LeadRealtime = () => {
@@ -332,7 +352,7 @@ their types are the exports of `@collective-intelligence/effect-xstate/actors`,
332
352
  which the package depends on at the release version, so the app, this SDK and
333
353
  the shared chat run one copy of the bridge.
334
354
 
335
- - `WriteFailed` is the type of the [`onWriteFailed`](#optimistic-writes) event.
355
+ - `WriteFailed` is the type of the [`onWriteFailed`](#record-writes) event.
336
356
  - `fromEffect(run)` makes actor logic from an Effect. The actor runs the effect
337
357
  on `input.runtime`, so annotate `input` with a `runtime: EffectRunner<R>`
338
358
  that provides every service of the effect. The actor's output is the
@@ -360,23 +380,8 @@ the shared chat run one copy of the bridge.
360
380
  `cancel(queryKey)` cancels the running fetches and interrupts their
361
381
  queries, so they write no value; it keeps the cached values and starts no
362
382
  fetch.
363
- `optimisticUpdate(queryKey, edit, write, options?)` is an optimistic write
364
- of one key: it runs `write` and gives its result. Each pending write of the
365
- key is a layer of its `edit` over the confirmed value, and views show the
366
- layers in call order at once. The writes to one key, of every `QueryCache`
367
- over the same QueryClient, go to CI one at a time in call order; when CI
368
- gets one, the running fetch of the key is cancelled, and a `write`
369
- function gets `{ confirmed, optimistic }` of that moment, so a refused
370
- write before it is not in its payload. A fetch that ends while writes are
371
- pending updates the confirmed value, and the layers show over it again.
372
- When CI confirms the write, the confirmed value becomes
373
- `options.confirm(result, confirmed)` or gets the edit; when `write` fails,
374
- is interrupted or dies, only its own layer goes. A value that `setData`,
375
- `update` or `remove` puts meanwhile stays, and the `confirm` of the writes
376
- before it does not run. Each run of the effect is one write. The key is invalidated
377
- when `write` ends, also when `confirm` throws. The QueryClient holds the
378
- writes, so two bundled copies of the SDK over it share them. `pending(queryKey)` gives the number of optimistic
379
- writes of the key that wait or run.
383
+ `QueryCache` has no optimistic write: write CI records through `RecordWrites` on a
384
+ Record Collection (`./records`).
380
385
  `setData(queryKey, value)` writes a value that views show at once.
381
386
  `update(queryKey, (current) => next)` replaces each cached value with the
382
387
  result of the function for its current value, without a refetch, for
package/dist/effect.d.ts CHANGED
@@ -6,7 +6,6 @@ import { QueryClient, QueryKey } from '@tanstack/react-query';
6
6
  import * as Context from 'effect/Context';
7
7
  import * as Effect from 'effect/Effect';
8
8
  import * as Layer from 'effect/Layer';
9
- import * as ManagedRuntime from 'effect/ManagedRuntime';
10
9
  import { ReactNode } from 'react';
11
10
 
12
11
  export type QueryCacheFetchOptions<Data> = Readonly<{
@@ -16,32 +15,6 @@ export type QueryCacheFetchOptions<Data> = Readonly<{
16
15
  /** Milliseconds for which a cached value stays fresh; without it, the QueryClient default applies. */
17
16
  staleTime?: number;
18
17
  }>;
19
- /** The values of the entry of a key when CI gets its optimistic write. */
20
- export type QueryCacheWriteValues<Data> = Readonly<{
21
- /**
22
- * CI's value of the key: the value of the last fetch with the answers of
23
- * the writes before this one, without any pending edit. `undefined` when
24
- * the entry has no value.
25
- */
26
- confirmed: Data | undefined;
27
- /**
28
- * `confirmed` with the edit of this write only, so a refused write before
29
- * it is not in it. `undefined` when the entry has no value.
30
- */
31
- optimistic: Data | undefined;
32
- }>;
33
- export type QueryCacheOptimisticOptions<Data, A> = Readonly<{
34
- /**
35
- * The confirmed value after CI confirms the write with `result`, for
36
- * example CI's row with its new revision in `confirmed`. Without it, or
37
- * when it gives `undefined`, the confirmed value gets the edit. It does not
38
- * run when `setData`, `update` or `remove` replaced the value of the key
39
- * after the edit: the newer value stays. When it throws, the write dies
40
- * with its error, and the key still shows its other layers and is
41
- * invalidated.
42
- */
43
- confirm?: (result: A, confirmed: Data | undefined) => Data | undefined;
44
- }>;
45
18
  declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-intelligence/external-apps-client-sdk-react/QueryCache", Readonly<{
46
19
  /**
47
20
  * The fresh cached value of `queryKey`, or the value of one run of `query`,
@@ -58,9 +31,7 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
58
31
  * interrupts their queries, so these fetches write no value. Keeps the
59
32
  * cached values and starts no fetch, so a view of a key whose first fetch
60
33
  * it cancels shows no value until the next fetch. Call it before an
61
- * optimistic `update`, so that a fetch that ends later does not replace the
62
- * new value, and `invalidate` when the write ends; `optimisticUpdate` does
63
- * these steps for one key.
34
+ * `update`, so that a fetch that ends later does not replace the new value.
64
35
  */
65
36
  cancel: (queryKey: QueryKey) => Effect.Effect<void>;
66
37
  /** Caches `data` as the value of `queryKey`; views show it at once. */
@@ -82,43 +53,6 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
82
53
  * keeps its last result until it renders again.
83
54
  */
84
55
  remove: (queryKey: QueryKey) => Effect.Effect<void>;
85
- /**
86
- * Runs `write`, the remote write of an optimistic edit of the entry of
87
- * `queryKey`, and gives its result. Each pending write of a key is a layer
88
- * of its edit over the confirmed value, CI's value of the key, and views
89
- * show the layers in call order at once; an entry without a value shows no
90
- * edit until a fetch gives it one. The writes to one key, of every
91
- * `QueryCache` over the same `QueryClient`, go to CI one at a time in call
92
- * order; writes to other keys, also keys below `queryKey`, do not wait.
93
- * The `QueryClient` holds these writes, so each bundled copy of the SDK
94
- * over it shares them. Each run of the returned effect is one write, so an
95
- * effect that runs twice writes twice.
96
- *
97
- * When CI gets the write, the running fetch of the key is cancelled, and a
98
- * `write` function is called with the `QueryCacheWriteValues` of that
99
- * moment: the confirmed value with the answers of the writes before it,
100
- * and that value with this edit only. A fetch that ends while writes are
101
- * pending updates the confirmed value, and the edits show over it again,
102
- * so each edit must give the same value for a value that already holds
103
- * it, for example set fields or replace a row by its id.
104
- *
105
- * When CI confirms the write, its layer goes, and the confirmed value
106
- * becomes `options.confirm(result, confirmed)` or gets the edit. When
107
- * `write` fails, is interrupted or dies, only its own layer goes: the
108
- * other layers show over the confirmed value. A value that `setData`,
109
- * `update` or `remove` puts while writes are pending stays: the edits
110
- * before it no longer show or roll back, and CI's answer to them does not
111
- * change the value. When the write ends, the key is invalidated, and its
112
- * views read it again. The key is the entry that `getQueryData` finds,
113
- * also with a `queryKeyHashFn` of the `QueryClient`.
114
- */
115
- optimisticUpdate: <Data, A, E, R>(queryKey: QueryKey, edit: (current: Data) => Data, write: Effect.Effect<A, E, R> | ((values: QueryCacheWriteValues<Data>) => Effect.Effect<A, E, R>), options?: QueryCacheOptimisticOptions<Data, A>) => Effect.Effect<A, E, R>;
116
- /**
117
- * The number of optimistic writes of `queryKey` that wait for CI or run,
118
- * of every `QueryCache` over the same `QueryClient`, also of another
119
- * bundled copy of the SDK. Keys below `queryKey` do not count.
120
- */
121
- pending: (queryKey: QueryKey) => Effect.Effect<number>;
122
56
  }>>;
123
57
  /**
124
58
  * The remote data of the app's `QueryClient`, as machine actors read and
package/dist/effect.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{effectTask,fromEffect}from"@collective-intelligence/effect-xstate/actors";import{CiError,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import{isCancelledError,QueryObserver}from"@tanstack/react-query";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Layer from"effect/Layer";import*as Schema from"effect/Schema";class QueryCache extends Context.Service()("@collective-intelligence/external-apps-client-sdk-react/QueryCache"){}var writesKey=Symbol.for("@collective-intelligence/query-cache/optimistic-writes/v1");var writesOf=(queryClient)=>queryClient[writesKey];var hashIn=(queryClient,queryKey)=>queryClient.defaultQueryOptions({queryKey}).queryHash;var supersede=(key)=>{for(const layer of key.layers){layer.shown=false}};var show=(queryClient,key)=>{if(key.confirmed===undefined){return}let shown=key.confirmed;for(const layer of key.layers){if(layer.shown){shown=layer.apply(shown)}}key.showing=true;try{queryClient.setQueryData(key.queryKey,shown)}finally{key.showing=false}};var keepLayers=(queryClient,keys)=>(event)=>{const key=keys.get(event.query.queryHash);if(key===undefined||key.showing){return}if(event.type==="removed"){key.confirmed=undefined;supersede(key);return}if(event.type!=="updated"){return}const{action}=event;if(action.type==="success"){key.confirmed=event.query.state.data;if(action.manual===true){supersede(key)}else{show(queryClient,key)}}else if(action.type==="setState"){if(event.query.state.data===undefined){key.confirmed=undefined;supersede(key)}else{show(queryClient,key)}}};var listen=(queryClient)=>{const keys=new Map;const client={keys,stop:queryClient.getQueryCache().subscribe(keepLayers(queryClient,keys))};Object.defineProperty(queryClient,writesKey,{configurable:true,value:client});return client};var dropLayer=(key,layer)=>{const index=key.layers.indexOf(layer);if(index===-1){return false}key.layers.splice(index,1);return true};var wakeFirst=(key)=>{key.layers[0]?.wake?.()};var turnOf=(key,layer)=>Effect.callback((resume)=>{if(key.layers[0]===layer){resume(Effect.undefined);return}layer.wake=()=>{layer.wake=undefined;resume(Effect.undefined)};return Effect.sync(()=>{layer.wake=undefined})});var forgetIfDone=(queryClient,key)=>{const client=writesOf(queryClient);if(key.layers.length>0||client?.keys.get(key.hash)!==key){return}client.keys.delete(key.hash);if(client.keys.size===0){client.stop();Reflect.deleteProperty(queryClient,writesKey)}};var addLayer=(queryClient,queryKey,layer)=>{const client=writesOf(queryClient)??listen(queryClient);const hash=hashIn(queryClient,queryKey);const key=client.keys.get(hash)??{confirmed:queryClient.getQueryData(queryKey),hash,layers:[],queryKey,showing:false};client.keys.set(hash,key);key.layers.push(layer);try{show(queryClient,key)}catch(error){dropLayer(key,layer);forgetIfDone(queryClient,key);throw error}return key};var make=(queryClient)=>{const fetchExit=async({query,...options},context)=>{try{return Exit.succeed(await queryClient.fetchQuery({...options,queryFn:({signal})=>Effect.runPromiseWith(context)(query,{signal}),retry:false}))}catch(error){if(isCancelledError(error)){return Exit.interrupt()}return Schema.is(CiError)(error)||Schema.is(CiTransportError)(error)?Exit.fail(error):Exit.die(error)}};const waitOn=(queryKey)=>Effect.sync(()=>new QueryObserver(queryClient,{enabled:false,queryKey}).subscribe(constVoid));return QueryCache.of({cancel:(queryKey)=>Effect.promise(()=>queryClient.cancelQueries({queryKey})),fetch:(options)=>Effect.flatMap(Effect.context(),(context)=>Effect.acquireUseRelease(waitOn(options.queryKey),()=>Effect.flatten(Effect.promise(()=>fetchExit(options,context))),(stopWaiting)=>Effect.sync(stopWaiting))),invalidate:(queryKey)=>Effect.promise(()=>queryClient.invalidateQueries({queryKey})),optimisticUpdate:(queryKey,edit,write,options)=>Effect.suspend(()=>{const layer={apply:edit,confirm:(confirmed,result)=>{if(!layer.shown){return confirmed}const answered=options?.confirm?.(result,confirmed);if(answered!==undefined){return answered}return confirmed===undefined?undefined:edit(confirmed)},send:(confirmed)=>Effect.isEffect(write)?write:write({confirmed,optimistic:confirmed===undefined?undefined:edit(confirmed)}),shown:true,wake:undefined};const keyLayer=layer;const settle=(key,exit)=>Effect.sync(()=>{dropLayer(key,keyLayer);const before=key.confirmed;try{if(Exit.isSuccess(exit)){key.confirmed=keyLayer.confirm(key.confirmed,exit.value)}}finally{if(layer.shown||key.confirmed!==before){show(queryClient,key)}queryClient.invalidateQueries({exact:true,queryKey})}});return Effect.acquireUseRelease(Effect.sync(()=>addLayer(queryClient,queryKey,keyLayer)),(key)=>turnOf(key,keyLayer).pipe(Effect.andThen(Effect.promise(()=>queryClient.cancelQueries({exact:true,queryKey})).pipe(Effect.andThen(Effect.suspend(()=>keyLayer.send(key.confirmed))),Effect.onExit((exit)=>settle(key,exit))))),(key)=>Effect.sync(()=>{if(dropLayer(key,keyLayer)&&layer.shown){show(queryClient,key)}wakeFirst(key);forgetIfDone(queryClient,key)}))}),pending:(queryKey)=>Effect.sync(()=>writesOf(queryClient)?.keys.get(hashIn(queryClient,queryKey))?.layers.length??0),remove:(queryKey)=>Effect.sync(()=>{queryClient.removeQueries({queryKey})}),setData:(queryKey,data)=>Effect.sync(()=>{queryClient.setQueryData(queryKey,data)}),update:(queryKey,updater)=>Effect.sync(()=>{queryClient.setQueriesData({queryKey},updater)})})};var layer=(queryClient)=>Layer.succeed(QueryCache,make(queryClient));import{QueryClient}from"@tanstack/react-query";import*as Effect2 from"effect/Effect";import*as Layer2 from"effect/Layer";var makeTestQueryCache=(options={})=>{const queryClient=options.queryClient??new QueryClient({defaultOptions:{queries:{gcTime:Infinity}}});for(const[queryKey,data]of options.seed??[]){queryClient.setQueryData(queryKey,data)}const real=make(queryClient);const overrides=options.overrides??{};const calls=[];const logged=(member,queryKey,run)=>Effect2.suspend(()=>{calls.push({member,queryKey});return run()});return{calls,layer:Layer2.succeed(QueryCache,QueryCache.of({cancel:(queryKey)=>logged("cancel",queryKey,()=>(overrides.cancel??real.cancel)(queryKey)),fetch:(fetchOptions)=>logged("fetch",fetchOptions.queryKey,()=>(overrides.fetch??real.fetch)(fetchOptions)),invalidate:(queryKey)=>logged("invalidate",queryKey,()=>(overrides.invalidate??real.invalidate)(queryKey)),optimisticUpdate:(queryKey,edit,write,writeOptions)=>logged("optimisticUpdate",queryKey,()=>(overrides.optimisticUpdate??real.optimisticUpdate)(queryKey,edit,write,writeOptions)),pending:(queryKey)=>logged("pending",queryKey,()=>(overrides.pending??real.pending)(queryKey)),remove:(queryKey)=>logged("remove",queryKey,()=>(overrides.remove??real.remove)(queryKey)),setData:(queryKey,data)=>logged("setData",queryKey,()=>(overrides.setData??real.setData)(queryKey,data)),update:(queryKey,updater)=>logged("update",queryKey,()=>(overrides.update??real.update)(queryKey,updater))})),queryClient}};import{EffectRuntimeProvider as BridgeRuntimeProvider,makeEffectRuntimeContext,useEffectRuntime as useBridgeRuntime}from"@collective-intelligence/effect-xstate/react";import{useQueryClient}from"@tanstack/react-query";import*as ManagedRuntime from"effect/ManagedRuntime";import{useMemo}from"react";import{jsx}from"react/jsx-runtime";var RuntimeContext=makeEffectRuntimeContext();var EffectRuntimeProvider=({children})=>{const queryClient=useQueryClient();const runtime=useMemo(()=>ManagedRuntime.make(layer(queryClient)),[queryClient]);return jsx(BridgeRuntimeProvider,{context:RuntimeContext,runtime,children})};var useEffectRuntime=()=>useBridgeRuntime(RuntimeContext);export{EffectRuntimeProvider,QueryCache,effectTask,fromEffect,makeTestQueryCache,useEffectRuntime};
2
+ import{effectTask,fromEffect}from"@collective-intelligence/effect-xstate/actors";import{CiError,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import{isCancelledError,QueryObserver}from"@tanstack/react-query";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Layer from"effect/Layer";import*as Schema from"effect/Schema";class QueryCache extends Context.Service()("@collective-intelligence/external-apps-client-sdk-react/QueryCache"){}var make=(queryClient)=>{const fetchExit=async({query,...options},context)=>{try{return Exit.succeed(await queryClient.fetchQuery({...options,queryFn:({signal})=>Effect.runPromiseWith(context)(query,{signal}),retry:false}))}catch(error){if(isCancelledError(error)){return Exit.interrupt()}return Schema.is(CiError)(error)||Schema.is(CiTransportError)(error)?Exit.fail(error):Exit.die(error)}};const waitOn=(queryKey)=>Effect.sync(()=>new QueryObserver(queryClient,{enabled:false,queryKey}).subscribe(constVoid));return QueryCache.of({cancel:(queryKey)=>Effect.promise(()=>queryClient.cancelQueries({queryKey})),fetch:(options)=>Effect.flatMap(Effect.context(),(context)=>Effect.acquireUseRelease(waitOn(options.queryKey),()=>Effect.flatten(Effect.promise(()=>fetchExit(options,context))),(stopWaiting)=>Effect.sync(stopWaiting))),invalidate:(queryKey)=>Effect.promise(()=>queryClient.invalidateQueries({queryKey})),remove:(queryKey)=>Effect.sync(()=>{queryClient.removeQueries({queryKey})}),setData:(queryKey,data)=>Effect.sync(()=>{queryClient.setQueryData(queryKey,data)}),update:(queryKey,updater)=>Effect.sync(()=>{queryClient.setQueriesData({queryKey},updater)})})};var layer=(queryClient)=>Layer.succeed(QueryCache,make(queryClient));import{QueryClient}from"@tanstack/react-query";import*as Effect2 from"effect/Effect";import*as Layer2 from"effect/Layer";var makeTestQueryCache=(options={})=>{const queryClient=options.queryClient??new QueryClient({defaultOptions:{queries:{gcTime:Infinity}}});for(const[queryKey,data]of options.seed??[]){queryClient.setQueryData(queryKey,data)}const real=make(queryClient);const overrides=options.overrides??{};const calls=[];const logged=(member,queryKey,run)=>Effect2.suspend(()=>{calls.push({member,queryKey});return run()});return{calls,layer:Layer2.succeed(QueryCache,QueryCache.of({cancel:(queryKey)=>logged("cancel",queryKey,()=>(overrides.cancel??real.cancel)(queryKey)),fetch:(fetchOptions)=>logged("fetch",fetchOptions.queryKey,()=>(overrides.fetch??real.fetch)(fetchOptions)),invalidate:(queryKey)=>logged("invalidate",queryKey,()=>(overrides.invalidate??real.invalidate)(queryKey)),remove:(queryKey)=>logged("remove",queryKey,()=>(overrides.remove??real.remove)(queryKey)),setData:(queryKey,data)=>logged("setData",queryKey,()=>(overrides.setData??real.setData)(queryKey,data)),update:(queryKey,updater)=>logged("update",queryKey,()=>(overrides.update??real.update)(queryKey,updater))})),queryClient}};import{EffectRuntimeProvider as BridgeRuntimeProvider,makeEffectRuntimeContext,useEffectRuntime as useBridgeRuntime}from"@collective-intelligence/effect-xstate/react";import{useQueryClient}from"@tanstack/react-query";import*as ManagedRuntime from"effect/ManagedRuntime";import{useMemo}from"react";import{jsx}from"react/jsx-runtime";var RuntimeContext=makeEffectRuntimeContext();var EffectRuntimeProvider=({children})=>{const queryClient=useQueryClient();const runtime=useMemo(()=>ManagedRuntime.make(layer(queryClient)),[queryClient]);return jsx(BridgeRuntimeProvider,{context:RuntimeContext,runtime,children})};var useEffectRuntime=()=>useBridgeRuntime(RuntimeContext);export{EffectRuntimeProvider,QueryCache,effectTask,fromEffect,makeTestQueryCache,useEffectRuntime};
@@ -0,0 +1,2 @@
1
+ import*as Cause from"effect/Cause";import*as Exit from"effect/Exit";import*as Schema from"effect/Schema";class RecordWriteRefused2 extends Schema.TaggedError()("RecordWriteRefused",{message:Schema.String}){}class RecordWriteConflict2 extends Schema.TaggedError()("RecordWriteConflict",{message:Schema.String}){}class RecordWriteOutcomeUnknown2 extends Schema.TaggedError()("RecordWriteOutcomeUnknown",{cause:Schema.optional(Schema.Defect()),message:Schema.String}){}class RecordSyncFailed2 extends Schema.TaggedError()("RecordSyncFailed",{cause:Schema.optional(Schema.Defect()),message:Schema.String,retrying:Schema.Boolean}){}var reportSyncFailure=(sync,ready,error)=>{if(ready&&error.retrying){sync.reportError(error);return}sync.fail(error)};var settledWrite=(exit)=>Exit.isFailure(exit)&&Cause.hasInterruptsOnly(exit.cause)?Exit.fail(new RecordWriteOutcomeUnknown2({message:"The write was interrupted before its answer arrived"})):exit;import{DbClient}from"@tanstack/db";import{hashKey}from"@tanstack/query-core";import*as ManagedRuntime from"effect/ManagedRuntime";import*as Schema2 from"effect/Schema";var RecordIdentityKey=Schema2.String.pipe(Schema2.brand("RecordIdentityKey"));var recordIdentityKey=(identity)=>RecordIdentityKey.make(hashKey([identity.applicationId,identity.organizationId,identity.userId]));var recordQueryScope=(key)=>["ci-records",key];var makeRecordIdentities=(options)=>{const entries=new Map;const closing=new Set;const open=(identity,key)=>{const dbClient=new DbClient;const runtime=ManagedRuntime.make(options.layer(identity,{dbClient,identity:key,queryClient:options.queryClient}));return{dispose:async()=>{await runtime.dispose();await dbClient.cleanup()},holders:0,records:{dbClient,identity,key,runtime}}};const close=(entry)=>{const{key}=entry.records;if(entries.get(key)!==entry){return}entries.delete(key);const closed=entry.dispose();closing.add(closed);const forget=async()=>{await Promise.allSettled([closed]);closing.delete(closed)};forget()};const entryOf=(identity)=>{const key=recordIdentityKey(identity);const known=entries.get(key);if(known!==undefined){return known}const entry=open(identity,key);entries.set(key,entry);return entry};const records=(identity)=>entryOf(identity).records;const retain=(identity)=>{const entry=entryOf(identity);entry.holders+=1;for(const other of entries.values()){if(other.holders===0){close(other)}}let released=false;return()=>{if(released){return}released=true;entry.holders-=1;queueMicrotask(()=>{if(entry.holders===0){close(entry)}})}};const idle=async()=>{if(closing.size===0){return}await Promise.allSettled(closing);await idle()};return{idle,records,retain}};import{collectionOptions}from"@tanstack/db";import*as Context4 from"effect/Context";import*as Effect7 from"effect/Effect";import*as FiberMap from"effect/FiberMap";import*as Layer3 from"effect/Layer";import*as Schema11 from"effect/Schema";import*as Scope2 from"effect/Scope";import{hashKey as hashKey2}from"@tanstack/query-core";var realtimeCollectionId=({filter,schema})=>`ci-records:${hashKey2(filter===undefined?["realtime",schema]:["realtime",schema,filter.field,filter.eq])}`;var queryCollectionId=(queryKey)=>`ci-records:${hashKey2(["query",...queryKey])}`;import{queryCollectionOptions}from"@tanstack/query-db-collection";import*as Effect from"effect/Effect";import*as Schema4 from"effect/Schema";import*as Context from"effect/Context";import*as Schema3 from"effect/Schema";var RecordId2=Schema3.String.pipe(Schema3.brand("RecordId"));var RecordRevision=Schema3.String.pipe(Schema3.brand("RecordRevision"));var IdempotencyKey2=Schema3.String.pipe(Schema3.brand("IdempotencyKey"));var recordRowSchema=(value)=>Schema3.Struct({id:RecordId2,revision:Schema3.NullOr(RecordRevision),value});class RealtimeChangeSource extends Context.Service()("@collective-intelligence/records/RealtimeChangeSource"){}class RecordWriteTransport extends Context.Service()("@collective-intelligence/records/RecordWriteTransport"){}var seedFreshnessMillis=60000;var seeded=new WeakMap;var markSeeded=(queryClient,state)=>{const cache=queryClient.getQueryCache();for(const dehydrated of state.queries){const query=cache.get(dehydrated.queryHash);if(query!==undefined&&!seeded.has(query)&&query.state.dataUpdatedAt===dehydrated.state.dataUpdatedAt){seeded.set(query,{at:Date.now(),updates:query.state.dataUpdateCount})}}};var seededStaleTime=(queryClient)=>(query)=>{const seed=seeded.get(query);if(seed!==undefined&&seed.updates===query.state.dataUpdateCount){return Math.max(0,seed.at+seedFreshnessMillis-query.state.dataUpdatedAt)}const fallback=queryClient.getDefaultOptions().queries?.staleTime;if(typeof fallback!=="function"){return fallback??0}const anyQuery=query;return fallback(anyQuery)};var queryRecordCollectionOptions=({context,id,options,queryClient})=>{const decode=Schema4.decodeUnknownEffect(Schema4.Array(recordRowSchema(options.schema)));const load=options.load.pipe(Effect.flatMap((records)=>decode(records).pipe(Effect.mapError((cause)=>new RecordSyncFailed2({cause,message:`A record of the Record Collection ${id} does not decode: ${cause.message}`,retrying:false})))),Effect.map((rows)=>[...rows]),Effect.withSpan("RecordCollections.query.load",{attributes:{"record.collection":id}}));return queryCollectionOptions({getKey:(row)=>row.id,id,queryClient,queryFn:async({signal})=>await Effect.runPromiseWith(context)(load,{signal}),queryKey:options.queryKey,staleTime:seededStaleTime(queryClient)})};import*as Arr from"effect/Array";import*as Effect3 from"effect/Effect";import{pipe}from"effect/Function";import*as Latch from"effect/Latch";import*as Option2 from"effect/Option";import*as Queue from"effect/Queue";import*as Ref from"effect/Ref";import*as Schedule from"effect/Schedule";import*as Schema6 from"effect/Schema";import*as Stream from"effect/Stream";import*as SubscriptionRef from"effect/SubscriptionRef";import*as Schema5 from"effect/Schema";var RecordPosition=Schema5.String.pipe(Schema5.brand("RecordPosition"));var RealtimeSyncMeta=Schema5.Struct({position:RecordPosition});import*as Cache from"effect/Cache";import*as Effect2 from"effect/Effect";import*as Exit2 from"effect/Exit";import*as Option from"effect/Option";var defaultIdReadsOptions={capacity:1000,timeToLive:"1 minute"};var holds=(read,revision)=>Option.isSome(read)&&read.value.revision===revision;var makeIdReads=Effect2.fnUntraced(function*(read,options=defaultIdReadsOptions){const cache=yield*Cache.makeWith(read,{capacity:options.capacity,timeToLive:(exit)=>Exit2.isFailure(exit)?0:options.timeToLive});return Effect2.fnUntraced(function*(id,revision){const kept=yield*Cache.getSuccess(cache,id);if(Option.isSome(kept)&&!holds(kept.value,revision)){yield*Cache.invalidate(cache,id)}return yield*Cache.get(cache,id)})});var defaultRealtimeSyncLimits={batchSize:100,batchWindow:"20 millis",queueCapacity:1000,readConcurrency:8};var isResync=(item)=>item._tag==="resync";var retrySchedule=Schedule.exponential("250 millis").pipe(Schedule.jittered,Schedule.upTo({duration:"60 seconds"}));var keep={_tag:"keep"};var firstLoadResync={_tag:"resync",generation:undefined,reason:"first-open"};var lastHintPerRecord=(batch)=>{const last=new Map;for(const item of batch){if(item._tag!=="resync"){last.delete(item.id);last.set(item.id,item)}}return[...last.values()]};var decodeSyncMeta=Schema6.decodeUnknownOption(RealtimeSyncMeta);var makeRealtimeStart=()=>{let current;return{exportSyncMeta:()=>current===undefined?undefined:{position:current},importSyncMeta:(meta)=>{const decoded=decodeSyncMeta(meta);if(Option2.isSome(decoded)){current=decoded.value.position}},keep:(position)=>Effect3.sync(()=>{current=position}),position:Effect3.sync(()=>current)}};var followTopic=Effect3.fn("RecordCollections.realtime.sync")(function*({limits,schema,source,start,sync:sync2,topic}){const ready=yield*Latch.make();const reads=yield*makeIdReads((id)=>source.read(topic,id));const decode=Schema6.decodeUnknownEffect(recordRowSchema(schema));const resyncs=yield*SubscriptionRef.make({count:0,generation:undefined});const uncovered=yield*Ref.make(Option2.none());const unread=yield*Ref.make([]);const hints=yield*Queue.bounded(limits.queueCapacity);const reportRecordFailure=(id,cause)=>Effect3.sync(()=>{reportSyncFailure(sync2,Latch.isOpen(ready),new RecordSyncFailed2({cause,message:`The record ${id} of the Realtime Record Collection ${sync2.collection.id} could not be read or decoded`,retrying:true}))});const rowWrite=(hint)=>{if(hint._tag!=="change"){return Effect3.succeed({_tag:"remove",id:hint.id})}if(sync2.collection.base.get(hint.id)?.revision===hint.revision){return Effect3.succeed(keep)}return reads(hint.id,hint.revision).pipe(Effect3.retry({schedule:retrySchedule,while:(failure)=>failure.retrying}),Effect3.tapError((failure)=>reportRecordFailure(hint.id,failure)),Effect3.matchEffect({onFailure:()=>Effect3.succeed({_tag:"unread",hint}),onSuccess:Option2.match({onNone:()=>Effect3.succeed({_tag:"remove",id:hint.id}),onSome:(record)=>decode(record).pipe(Effect3.map((row)=>({_tag:"write",row})),Effect3.tapError((failure)=>reportRecordFailure(hint.id,failure)),Effect3.orElseSucceed(()=>keep))})}))};const rowOf=(record)=>decode(record).pipe(Effect3.asSome,Effect3.tapError((failure)=>reportRecordFailure(RecordId2.make(record.id),failure)),Effect3.orElseSucceed(Option2.none));const loadTopic=Effect3.fnUntraced(function*(){const{position,records}=yield*source.load(topic);const rows=yield*Effect3.forEach(records,rowOf);sync2.begin({snapshot:true});for(const row of rows){if(Option2.isSome(row)){sync2.write({type:"insert",value:row.value})}}sync2.commit();yield*start.keep(position)});const reload=Effect3.fn("RecordCollections.realtime.reload")(function*(resync,seen,wasUncovered){yield*Effect3.annotateCurrentSpan({"record.collection":sync2.collection.id,"record.resync.count":seen.count,"record.resync.generation":resync.generation??"client","record.resync.reason":resync.reason,"record.resync.uncovered":wasUncovered});yield*loadTopic().pipe(Effect3.retry({schedule:retrySchedule,while:(failure)=>failure.retrying}))},Effect3.as(true),Effect3.tapError((failure)=>Effect3.sync(()=>{reportSyncFailure(sync2,Latch.isOpen(ready),failure)})),Effect3.orElseSucceed(()=>false));const firstLoad=Effect3.fn("RecordCollections.realtime.firstLoad")(function*(){yield*Effect3.annotateCurrentSpan({"record.collection":sync2.collection.id});yield*loadTopic()},Effect3.as(undefined),Effect3.catch(Effect3.succeed));const firstLoadFailure=(yield*start.position)===undefined&&sync2.collection.base.size===0?yield*firstLoad():undefined;const applyBatch=Effect3.fnUntraced(function*(batch){const seen=yield*SubscriptionRef.get(resyncs);const items=[...yield*Ref.getAndSet(unread,[]),...batch];const lastResync=pipe(items,Arr.findLast(isResync));const pending=yield*Ref.get(uncovered);const toCover=Option2.orElse(lastResync,()=>pending);const covered=Option2.isSome(toCover)?yield*reload(toCover.value,seen,Option2.isSome(pending)):false;yield*Ref.set(uncovered,covered?Option2.none():toCover);const after=pipe(items,Arr.findLastIndex(isResync),Option2.filter(()=>covered),Option2.match({onNone:()=>items,onSome:(last)=>items.slice(last+1)}));const writes=yield*Effect3.forEach(lastHintPerRecord(after),rowWrite,{concurrency:limits.readConcurrency});const changed=[];const failed=[];for(const write of writes){if(write._tag==="unread"){failed.push(write.hint)}else if(write._tag!=="keep"){changed.push(write)}}yield*Effect3.annotateCurrentSpan({"record.hints":batch.length,"record.hints.unread":failed.length});const now=yield*SubscriptionRef.get(resyncs);if(now.count!==seen.count){return}yield*Ref.set(unread,failed);if(changed.length===0){return}sync2.begin();for(const write of changed){sync2.write(write._tag==="write"?{type:"update",value:write.row}:{key:write.id,type:"delete"})}sync2.commit()});yield*Stream.concat(firstLoadFailure===undefined?Stream.empty:Stream.make(firstLoadResync),source.changes(topic,start.position)).pipe(Stream.tap((item)=>isResync(item)?SubscriptionRef.update(resyncs,(seen)=>({count:seen.count+1,generation:item.generation})):Effect3.void),Stream.onStart(Effect3.andThen(Latch.open(ready),Effect3.sync(()=>{sync2.markReady();if(firstLoadFailure!==undefined){reportSyncFailure(sync2,true,firstLoadFailure)}}))),Stream.runIntoQueue(hints),Effect3.forkScoped);yield*Stream.fromQueue(hints).pipe(Stream.groupedWithin(limits.batchSize,limits.batchWindow),Stream.mapEffect(applyBatch,{concurrency:1}),Stream.runDrain,Effect3.catch((error)=>Effect3.sync(()=>{reportSyncFailure(sync2,Latch.isOpen(ready),error)})))},Effect3.scoped);import*as Option3 from"effect/Option";import*as Schema7 from"effect/Schema";var registries=new WeakMap;var registerTargetCollection=(dbClient,target,registered)=>{const collection=registered.collection;const entry={...registered,collection};const registry=registries.get(dbClient)??new Map;registries.set(dbClient,registry);const collections=registry.get(target.key)??new Map;registry.set(target.key,collections);collections.set(entry.collection,entry)};var targetCollections=(dbClient,target)=>{const collections=registries.get(dbClient)?.get(target.key);if(collections===undefined){return[]}const open=[...collections.values()].filter(({collection})=>collection.status!=="cleaned-up"&&collection.status!=="error");return[...open.filter(({kind})=>kind==="realtime"),...open.filter(({kind})=>kind==="query")]};var decodeFields=Schema7.decodeUnknownOption(Schema7.Record(Schema7.String,Schema7.Unknown));var fieldsOf=(record)=>Array.isArray(record.value)?Option3.none():decodeFields(record.value);var topicMembership=(topic)=>(record)=>{const{filter}=topic;if(filter===undefined){return"in"}if(Option3.isNone(fieldsOf(record))){return"unknown"}const path=filter.field.split(".");let current=record.value;for(const key of path){const fields=fieldsOf({value:current});if(Option3.isNone(fields)){return"out"}if(!Object.hasOwn(fields.value,key)){return"unknown"}current=fields.value[key]}if(Array.isArray(current)){return path.length===1&&current.includes(filter.eq)?"in":"out"}return current===filter.eq?"in":"out"};import{whenSyncAccepted}from"@tanstack/db";import*as Cause3 from"effect/Cause";import*as Context3 from"effect/Context";import*as Effect6 from"effect/Effect";import*as Exit4 from"effect/Exit";import*as Layer2 from"effect/Layer";import*as Option5 from"effect/Option";import*as Schedule2 from"effect/Schedule";import*as Schema10 from"effect/Schema";import{createCollection,localOnlyCollectionOptions,safeRandomUUID}from"@tanstack/db";import{IndexedDBAdapter,LocalStorageAdapter,NonRetriableError,OfflineTransactionAPI,startOfflineExecutor,WebLocksLeader}from"@tanstack/offline-transactions";import*as Cause2 from"effect/Cause";import*as Context2 from"effect/Context";import*as Effect4 from"effect/Effect";import*as Exit3 from"effect/Exit";import*as Layer from"effect/Layer";import*as Option4 from"effect/Option";import*as Schema8 from"effect/Schema";var OrganizationId=Schema8.String.pipe(Schema8.brand("OrganizationId"));var UserId=Schema8.String.pipe(Schema8.brand("UserId"));var OutboxStorageKey=Schema8.String.pipe(Schema8.brand("OutboxStorageKey"));var outboxStorageKey=(organizationId,userId)=>OutboxStorageKey.make(`ci-records:${organizationId}:${userId}`);var StoredTarget=Schema8.Struct({key:Schema8.String});var After=Schema8.optional(IdempotencyKey2);var OutboxEntry=Schema8.Struct({after:After,followed:Schema8.optional(Schema8.Boolean),key:IdempotencyKey2,write:Schema8.Union([Schema8.Struct({kind:Schema8.Literal("create"),request:Schema8.Struct({id:Schema8.optionalKey(RecordId2),idempotencyKey:IdempotencyKey2,target:StoredTarget,value:Schema8.Unknown})}),Schema8.Struct({kind:Schema8.Literal("update"),request:Schema8.Struct({change:Schema8.Unknown,expectedRevision:Schema8.NullOr(RecordRevision),id:RecordId2,idempotencyKey:IdempotencyKey2,target:StoredTarget})}),Schema8.Struct({kind:Schema8.Literal("delete"),request:Schema8.Struct({expectedRevision:Schema8.NullOr(RecordRevision),id:RecordId2,idempotencyKey:IdempotencyKey2,target:StoredTarget})})])});var HeldWrite=Schema8.fromJsonString(Schema8.Struct({after:After,idempotencyKey:IdempotencyKey2,storedAt:Schema8.Finite,write:OutboxEntry.fields.write}));var SettledRecord=Schema8.Struct({id:RecordId2,revision:Schema8.NullOr(RecordRevision)});var StoredSettledRecord=Schema8.fromJsonString(SettledRecord);var settledKey=(key)=>`settled:${key}`;var settledRecordOf=(write,answer)=>{if(answer!==undefined){return{id:answer.id,revision:answer.revision}}if(write.kind==="create"){return{id:write.request.id??RecordId2.make(write.request.idempotencyKey),revision:null}}return{id:write.request.id,revision:write.request.expectedRevision}};var behind=(write,settled)=>{if(settled===undefined||write.kind==="create"){return write}const record={expectedRevision:settled.revision,id:settled.id};return write.kind==="update"?{kind:"update",request:{...write.request,...record}}:{kind:"delete",request:{...write.request,...record}}};var heldPrefix="held:";var heldKey=(page,key)=>`${heldPrefix}${page}:${key}`;var heldPageOf=(storageKey)=>storageKey.startsWith(heldPrefix)?storageKey.slice(heldPrefix.length).split(":",1)[0]:undefined;var makeOutboxPage=()=>({id:safeRandomUUID(),writes:new Map});var thisPage=makeOutboxPage();class RecordOutbox extends Context2.Service()("@collective-intelligence/records/RecordOutbox"){}var withoutOutbox=(transport)=>({queue:()=>Effect4.void,transport,unqueue:()=>Effect4.void});var writeFunction="ci-records/write";var withTarget=(entry,target)=>{const{write}=entry;if(write.kind==="create"){return{kind:"create",request:{...write.request,target}}}if(write.kind==="update"){return{kind:"update",request:{...write.request,target}}}return{kind:"delete",request:{...write.request,target}}};var storedEntry=(write)=>{const key=write.request.idempotencyKey;const target={key:write.request.target.key};if(write.kind==="create"){return{key,write:{kind:"create",request:{...write.request,target}}}}if(write.kind==="update"){return{key,write:{kind:"update",request:{...write.request,target}}}}return{key,write:{kind:"delete",request:{...write.request,target}}}};var observedStorage=(base)=>{const waiters=new Map;const removals=new Map;let closed=false;const adapter={clear:async()=>{await base.clear()},delete:async(key)=>{await base.delete(key);const removed=removals.get(key);removals.delete(key);await removed?.()},get:async(key)=>await base.get(key),keys:async()=>await base.keys(),set:async(key,value)=>{if(closed){return}await base.set(key,value);waiters.get(key)?.();waiters.delete(key)}};const stored=async(key)=>{await new Promise((resolve)=>{waiters.set(key,resolve)});return true};const close=()=>{closed=true};const whenDeleted=(key,task)=>{removals.set(key,task)};return{adapter,close,forget:(key)=>waiters.delete(key),stored,whenDeleted}};var webLocks=()=>WebLocksLeader.isSupported();var nothing=()=>{};var webLocksLeader=(name)=>{const listeners=new Set;let leader=false;let release;let waiting;const tell=(next)=>{if(leader===next){return}leader=next;for(const listener of listeners){listener(next)}};const hold=async()=>{await new Promise((resolve)=>{release=resolve})};return{isLeader:()=>leader,onLeadershipChange:(listener)=>{listeners.add(listener);if(leader){queueMicrotask(()=>{if(listeners.has(listener)){listener(true)}})}return()=>{listeners.delete(listener)}},releaseLeadership:()=>{waiting?.abort();waiting=undefined;release?.();release=undefined;tell(false)},requestLeadership:async()=>{if(leader||waiting!==undefined){return leader}const acquired=await new Promise((resolve)=>{(async()=>{try{await navigator.locks.request(name,{ifAvailable:true},async(lock)=>{resolve(lock!==null);if(lock!==null){await hold()}})}catch{resolve(false)}})()});if(acquired){leader=true;return true}waiting=new AbortController;const{signal}=waiting;(async()=>{try{await navigator.locks.request(name,{signal},async()=>{tell(true);await hold()})}catch{}})();return false}}};var pageLock=(page)=>`ci-records-page:${page}`;var pageHolds=new Map;var browserTabs=(key)=>{const channels=webLocks()&&"BroadcastChannel"in globalThis;return{announce:()=>{if(!channels){return}const channel=new BroadcastChannel(key);channel.postMessage("stored");channel.close()},gone:async(page,signal)=>{if(!webLocks()){return}try{await navigator.locks.request(pageLock(page),{signal},()=>{})}catch{}},hold:(page)=>{if(!webLocks()){return nothing}const known=pageHolds.get(page);if(known===undefined){let release=nothing;const held=new Promise((resolve)=>{release=resolve});navigator.locks.request(pageLock(page),async()=>{await held});pageHolds.set(page,{count:1,release})}else{known.count+=1}let released=false;return()=>{const current=pageHolds.get(page);if(released||current===undefined){return}released=true;current.count-=1;if(current.count===0){pageHolds.delete(page);current.release()}}},onAnnounce:(listener)=>{if(!channels){return nothing}const channel=new BroadcastChannel(key);channel.addEventListener("message",()=>{listener()});return()=>{channel.close()}}}};var thisTab={isLeader:()=>true,onLeadershipChange:()=>()=>{},releaseLeadership:()=>{},requestLeadership:async()=>await Promise.resolve(true)};var committedFirst=async(commit)=>{try{await commit}catch{}return false};var isFinal=Schema8.is(Schema8.Union([RecordWriteRefused2,RecordWriteConflict2]));var settledBy=(write,exit)=>{if(Exit3.isSuccess(exit)){return settledRecordOf(write,exit.value)}const failure=Cause2.findErrorOption(exit.cause);return Option4.isSome(failure)&&isFinal(failure.value)?settledRecordOf(write):undefined};var messageOf=(cause)=>{const error=Cause2.squash(cause);return error instanceof Error?error.message:String(error)};var make7=(options)=>RecordOutbox.of({attach:Effect4.fnUntraced(function*({transport,resend}){const base=yield*Effect4.promise(options.storage);if(base===undefined){return withoutOutbox(transport)}const context2=yield*Effect4.context();const storage=observedStorage(base);const entries=createCollection(localOnlyCollectionOptions({getKey:(entry)=>entry.key,id:options.key}));const page=options.page??thisPage;const tabs=options.tabs??browserTabs(options.key);const releasePage=tabs.hold(page.id);const own=(key)=>`${options.key} ${key}`;const stopping=new AbortController;let lastStore=0;let storing=Promise.resolve();const serially=async(task)=>{const previous=storing;const next=(async()=>{await previous;await task()})();storing=(async()=>{try{await next}catch{}})();await next};const laterMillisecond=async()=>{while(Date.now()<=lastStore){const wait=lastStore+1-Date.now();await new Promise((resolve)=>{setTimeout(resolve,wait)})}};const persist=async(key,held)=>{const value=await Effect4.runPromiseWith(context2)(Schema8.encodeEffect(HeldWrite)({after:held.after,idempotencyKey:key,storedAt:held.storedAt,write:storedEntry(held.write).write}));await storage.adapter.set(heldKey(page.id,key),value)};const ownPrefix=own("");const fill=async(key,record)=>{for(const[pageKey,held]of page.writes){if(!pageKey.startsWith(ownPrefix)||!held.waiting||held.after!==key){continue}const filled={after:undefined,storedAt:held.storedAt,waiting:true,write:behind(held.write,record)};page.writes.set(pageKey,filled);try{await persist(held.write.request.idempotencyKey,filled)}catch{}}};const settledOf=async(key)=>{const value=await storage.adapter.get(settledKey(key));const decoded=await Effect4.runPromiseExitWith(context2)(Schema8.decodeUnknownEffect(StoredSettledRecord)(value));return Exit3.isSuccess(decoded)?decoded.value:undefined};const replayed=async(entry,storageKey,record)=>{if(entry.followed===true){const value=await Effect4.runPromiseWith(context2)(Schema8.encodeEffect(StoredSettledRecord)(record));await storage.adapter.set(settledKey(entry.key),value)}await serially(async()=>{await fill(entry.key,record)});const{after}=entry;if(after!==undefined){storage.whenDeleted(storageKey,async()=>{await base.delete(settledKey(after))})}};const replay=Effect4.fn("RecordOutbox.send")(function*(transactionId,mutations){const entry=yield*Schema8.decodeUnknownEffect(OutboxEntry)(mutations[0]?.modified).pipe(Effect4.mapError((cause)=>new RecordWriteRefused2({message:`The stored write does not decode: ${cause.message}`})));yield*Effect4.annotateCurrentSpan({"record.idempotency_key":entry.key,"record.target":entry.write.request.target.key,"write.kind":entry.write.kind});const target=yield*Effect4.fromNullishOr(options.target(entry.write.request.target.key)).pipe(Effect4.mapError(()=>new RecordWriteOutcomeUnknown2({message:`The write target ${entry.write.request.target.key} is not known yet`})));const{after}=entry;const settled=after===undefined?undefined:yield*Effect4.promise(async()=>await settledOf(after));const write=behind(withTarget(entry,target),settled);const exit2=yield*Effect4.exit(resend(write));const outcome=settledBy(write,exit2);if(outcome!==undefined){yield*Effect4.promise(async()=>{await replayed(entry,`tx:${transactionId}`,outcome)})}return yield*exit2});const send=async({transaction})=>{const exit=await Effect4.runPromiseExitWith(context2)(replay(transaction.id,transaction.mutations),{signal:stopping.signal});if(Exit3.isSuccess(exit)){return}const failure=Cause2.findErrorOption(exit.cause);if(Option4.isSome(failure)&&isFinal(failure.value)){throw new NonRetriableError(failure.value.message)}const retry=new Error(messageOf(exit.cause));retry.stack="";throw retry};const leadership={gained:()=>{}};const config={collections:{[options.key]:entries},leaderElection:options.leaderElection??(webLocks()?webLocksLeader(options.key):thisTab),mutationFns:{[writeFunction]:send},onLeadershipChange:(isLeader)=>{if(isLeader){leadership.gained()}},shouldRetry:()=>true,storage:storage.adapter};if(options.onlineDetector!==undefined){config.onlineDetector=options.onlineDetector}const executor=startOfflineExecutor(config);const enqueue=async(entry)=>{await laterMillisecond();const transaction=executor.createOfflineTransaction({autoCommit:false,idempotencyKey:entry.key,mutationFnName:writeFunction});if(!(transaction instanceof OfflineTransactionAPI)){transaction.rollback();return false}const storageKey=`tx:${transaction.id}`;const stored=storage.stored(storageKey);try{transaction.mutate(()=>{entries.insert(entry)})}catch{storage.forget(storageKey);transaction.rollback();return false}const done=await Promise.race([stored,committedFirst(transaction.commit())]);storage.forget(storageKey);lastStore=Date.now();return done};const adopt=async(gone)=>{const prefix=heldKey(gone,"");const all=await storage.adapter.keys();const keys=all.filter((key)=>key.startsWith(prefix));const held=await Promise.all(keys.map(async(storageKey)=>{const value=await storage.adapter.get(storageKey);const decoded=await Effect4.runPromiseExitWith(context2)(Schema8.decodeUnknownEffect(HeldWrite)(value));return{decoded,storageKey}}));const writes=[];for(const{decoded,storageKey}of held){if(Exit3.isSuccess(decoded)){writes.push({storageKey,write:decoded.value})}else{await storage.adapter.delete(storageKey)}}writes.sort((a,b)=>a.write.storedAt-b.write.storedAt);const followed=new Set(writes.map(({write})=>write.after));const inExecutor=await executor.peekOutbox();const queued=new Set(inExecutor.map((each)=>each.idempotencyKey));for(const{storageKey,write}of writes){if(!executor.isOfflineEnabled||stopping.signal.aborted){return}if(!queued.has(write.idempotencyKey)){const stored=await enqueue({after:write.after,followed:followed.has(write.idempotencyKey),key:write.idempotencyKey,write:write.write});if(!stored){return}}await storage.adapter.delete(storageKey)}};const watched=new Set;const watchPages=async()=>{try{await executor.waitForInit()}catch{return}if(!executor.isOfflineEnabled||stopping.signal.aborted){return}for(const key of await storage.adapter.keys()){const other=heldPageOf(key);if(other===undefined||other===page.id||watched.has(other)){continue}watched.add(other);(async()=>{try{await tabs.gone(other,stopping.signal);if(executor.isOfflineEnabled&&!stopping.signal.aborted){await serially(async()=>{await adopt(other)})}}catch{}finally{watched.delete(other)}})()}};leadership.gained=()=>{watchPages()};const unsubscribe=tabs.onAnnounce(()=>{watchPages()});yield*Effect4.addFinalizer(()=>Effect4.promise(async()=>{unsubscribe();executor.dispose();storage.close();stopping.abort();releasePage();await entries.cleanup()}));const store=async(write,after)=>{await laterMillisecond();const key=write.request.idempotencyKey;const held={after,storedAt:Date.now(),waiting:after!==undefined,write};page.writes.set(own(key),held);try{await persist(key,held);tabs.announce()}catch{page.writes.delete(own(key))}lastStore=Date.now()};const sending=async(write,held)=>{const key=write.request.idempotencyKey;const exact={after:undefined,storedAt:held.storedAt,waiting:false,write};page.writes.set(own(key),exact);try{await persist(key,exact)}catch{}};const release=async(key)=>{if(!page.writes.delete(own(key))){return}try{await storage.adapter.delete(heldKey(page.id,key))}catch{}};const journal=(writeOf,sendWrite)=>Effect4.fnUntraced(function*(request){const key=request.idempotencyKey;const write=writeOf(request);const held=page.writes.get(own(key));if(held===undefined||held.waiting){yield*Effect4.promise(async()=>{await serially(async()=>{await(held===undefined?store(write):sending(write,held))})})}const settle=(answer)=>Effect4.promise(async()=>{await serially(async()=>{await fill(key,settledRecordOf(write,answer))});await release(key)});return yield*sendWrite(request).pipe(Effect4.tap((answer)=>settle(answer)),Effect4.tapError((error)=>isFinal(error)?settle():Effect4.void))});const queue=(write,after)=>Effect4.promise(async()=>{if(page.writes.has(own(write.request.idempotencyKey))){return}await serially(async()=>{await store(write,after)})});const unqueue=(key)=>Effect4.promise(async()=>{if(page.writes.get(own(key))?.waiting===true){await release(key)}});const sends=RecordWriteTransport.of({create:journal((request)=>({kind:"create",request}),transport.create),delete:journal((request)=>({kind:"delete",request}),transport.delete),update:journal((request)=>({kind:"update",request}),transport.update)});return{queue,transport:sends,unqueue}})});var layer=(options)=>Layer.succeed(RecordOutbox,make7(options));var browserOutboxStorage=async(key)=>{const indexedDB=await IndexedDBAdapter.probe();if(indexedDB.available){return new IndexedDBAdapter(key)}if(LocalStorageAdapter.probe().available){return new LocalStorageAdapter(`${key}:`)}return};var dropOutbox=async(key)=>{const storage=await browserOutboxStorage(key);await storage?.clear()};import*as Effect5 from"effect/Effect";import*as RcMap from"effect/RcMap";import*as Schema9 from"effect/Schema";import*as Scope from"effect/Scope";import*as Semaphore from"effect/Semaphore";var writeLockRegistryKey=Symbol.for("@collective-intelligence/records/write-lock/v1");var RecordLockKey=Schema9.String.pipe(Schema9.brand("RecordLockKey"));var recordLockKey=(target,id)=>RecordLockKey.make(`${target.key}#${id}`);var idleTimeToLive="30 seconds";var makeRegistry=()=>{const locks=Effect5.runSync(RcMap.make({idleTimeToLive,lookup:(_key)=>Semaphore.make(1)}).pipe(Scope.provide(Scope.makeUnsafe())));return{withRecord:(key)=>(self)=>Effect5.scoped(Effect5.flatMap(RcMap.get(locks,key),(lock)=>lock.withPermit(self)))}};var isRegistry=(value)=>typeof value==="object"&&value!==null&&("withRecord"in value);var writeLock=()=>{const registered=Reflect.get(globalThis,writeLockRegistryKey);if(isRegistry(registered)){return registered}const registry=makeRegistry();Reflect.set(globalThis,writeLockRegistryKey,registry);return registry};var confirmedRowsByCollection=new WeakMap;var acceptConfirmedRows=(collection,rows)=>{confirmedRowsByCollection.set(collection,rows)};var syncConfirmedRows=(sync,schema)=>({put:(row)=>{sync.begin();sync.write({type:"update",value:row});return sync.commit()},remove:(id)=>{sync.begin();sync.write({key:id,type:"delete"});return sync.commit()},schema});class RecordWrites2 extends Context3.Service()("@collective-intelligence/records/RecordWrites"){}var missingRow=(input)=>new RecordWriteRefused2({message:`The record ${input.id} is not in the Record Collection ${input.collection.id}`});var acceptedRowsOf=(collection)=>confirmedRowsByCollection.get(collection);var confirmedRowsOf=(input)=>{const rows=acceptedRowsOf(input.collection);return rows===undefined?Effect6.die(new Error(`The collection ${input.collection.id} takes no confirmed rows: its sync must call acceptConfirmedRows`)):Effect6.succeed(rows)};var accepted=(receipt)=>{const acceptance=whenSyncAccepted(receipt);return acceptance===true?Effect6.void:Effect6.promise(async()=>{await acceptance})};var keepsAll=()=>true;var putOrRemove=(rows,keeps,row,answer)=>accepted(keeps(answer)?rows.put(row):rows.remove(row.id));var replaces=(showing,revision,answer,confirming)=>{if(!confirming.resent){return true}if(showing.kind==="realtime"||revision===undefined){return false}return revision===null||revision===confirming.base||revision===answer.revision};var refetch=(collection)=>{const{refetch:read}=collection.utils;return read===undefined?Effect6.void:Effect6.asVoid(Effect6.forkDetach(Effect6.ignore(Effect6.tryPromise(read))))};var readAgain=(showing,confirming)=>!confirming.resent||showing.kind==="realtime"?Effect6.void:refetch(showing.collection);var readQueriesAgain=(dbClient,target)=>Effect6.forEach(targetCollections(dbClient,target).filter(({kind})=>kind==="query"),({collection})=>refetch(collection),{discard:true});var confirm=Effect6.fnUntraced(function*(rows,showing,answer,confirming){const value=yield*Schema10.decodeUnknownEffect(rows.schema)(answer.value).pipe(Effect6.orDie);const row={id:answer.id,revision:answer.revision,value};const shown=showing.collection.get(answer.id)?.revision;if(replaces(showing,shown,answer,confirming)){yield*putOrRemove(rows,showing.keeps,row,answer)}yield*readAgain(showing,confirming);return row});var confirmShown=(shown,answer,confirming)=>Effect6.forEach(shown,(showing)=>{const rows=acceptedRowsOf(showing.collection);if(rows===undefined||!replaces(showing,showing.collection.get(answer.id)?.revision,answer,confirming)){return readAgain(showing,confirming)}return Schema10.decodeUnknownOption(rows.schema)(answer.value).pipe(Option5.match({onNone:()=>Effect6.void,onSome:(value)=>putOrRemove(rows,showing.keeps,{id:answer.id,revision:answer.revision,value},answer)}),Effect6.andThen(readAgain(showing,confirming)))},{discard:true});var removeShown=(shown,id,answer,confirming)=>Effect6.forEach(shown,(showing)=>{const rows=acceptedRowsOf(showing.collection);const removal=rows===undefined||!replaces(showing,showing.revision,answer,confirming)?Effect6.void:accepted(rows.remove(id));return Effect6.andThen(removal,readAgain(showing,confirming))},{discard:true});var showIn=(entries,change)=>{const shown=[];for(const entry of entries){try{change(entry.collection);shown.push(entry)}catch{}}return shown};var othersOf=(dbClient,input,includes)=>{const own=input.collection;return targetCollections(dbClient,input.target).filter((entry)=>entry.collection!==own&&includes(entry))};var ownShowing=(dbClient,input)=>{const own=input.collection;const entry=targetCollections(dbClient,input.target).find((each)=>each.collection===own);return{collection:own,keeps:entry?.keeps??keepsAll,kind:entry?.kind}};var attemptTimeout="15 seconds";var resendSchedule=Schedule2.exponential("250 millis").pipe(Schedule2.jittered,Schedule2.upTo({duration:"60 seconds"}));var isOutcomeUnknown=Schema10.is(RecordWriteOutcomeUnknown2);var untilAnswered=(attempt)=>attempt.pipe(Effect6.timeoutOrElse({duration:attemptTimeout,orElse:()=>Effect6.fail(new RecordWriteOutcomeUnknown2({message:`CI did not answer the write within ${attemptTimeout}`}))}),Effect6.retry({schedule:resendSchedule,while:isOutcomeUnknown}));var mutation=Effect6.fn("RecordWrites.mutationFn")(function*(send){return yield*send});var learnStoreId=(storeIds,target,clientId,answer)=>Effect6.sync(()=>{if(clientId!==undefined&&answer.id!==clientId){storeIds.set(recordLockKey(target,clientId),answer.id)}});var atStoreId=(storeIds,input,write)=>{const id=storeIds.get(recordLockKey(input.target,input.id));return id===undefined?write(input):Effect6.annotateCurrentSpan({"record.store_id":id}).pipe(Effect6.andThen(writeLock().withRecord(recordLockKey(input.target,id))(write({...input,id}))))};var makeLine=()=>{const last=new Map;return(key,idempotencyKey,queue,effect)=>Effect6.suspend(()=>{const ahead=last.get(key);last.set(key,idempotencyKey);const queued=ahead!==undefined&&queue!==undefined;return(queued?Effect6.andThen(queue.queue(ahead),effect):effect).pipe(Effect6.onExit((exit)=>{if(last.get(key)===idempotencyKey){last.delete(key)}return queued&&Exit4.isFailure(exit)&&!Cause3.hasInterruptsOnly(exit.cause)?queue.unqueue:Effect6.void}))})};var resendWith=(dbClient,transport,storeIds,inLine)=>(write)=>{const{request}=write;const key=recordLockKey(request.target,request.id??RecordId2.make(request.idempotencyKey));const send=Effect6.suspend(()=>{if(write.kind==="create"){return untilAnswered(transport.create(write.request)).pipe(Effect6.tap((answer)=>learnStoreId(storeIds,request.target,write.request.id,answer)))}if(write.kind==="update"){return atStoreId(storeIds,write.request,(stored)=>untilAnswered(transport.update(stored)))}return atStoreId(storeIds,write.request,(stored)=>untilAnswered(transport.delete(stored)))});return inLine(key,request.idempotencyKey,undefined,writeLock().withRecord(key)(send)).pipe(Effect6.tap(()=>readQueriesAgain(dbClient,request.target)),Effect6.withSpan("RecordWrites.resend",{attributes:{"record.idempotency_key":request.idempotencyKey,"record.key":key,"write.kind":write.kind}}))};var updateRequestOf=(input,row,lost)=>{if(lost?.kind==="update"){return lost.request}return row===undefined?undefined:{change:input.change,expectedRevision:row.revision,id:input.id,idempotencyKey:input.idempotencyKey,target:input.target}};var deleteRequestOf=(input,row,lost)=>{if(lost?.kind==="delete"){return lost.request}return row===undefined?undefined:{expectedRevision:row.revision,id:input.id,idempotencyKey:input.idempotencyKey,target:input.target}};var answerLost=(exit)=>Exit4.isFailure(exit)&&(Cause3.hasInterruptsOnly(exit.cause)||Option5.exists(Cause3.findErrorOption(exit.cause),isOutcomeUnknown));var make10=(options)=>Effect6.gen(function*(){const sender=yield*RecordWriteTransport;const storeIds=new Map;const unanswered=new Map;const sendKept=(write,send)=>untilAnswered(send).pipe(Effect6.onExit((exit)=>Effect6.sync(()=>{const key=write.request.idempotencyKey;if(answerLost(exit)){unanswered.set(key,write)}else{unanswered.delete(key)}})));const outbox=yield*Effect6.serviceOption(RecordOutbox);const inLine=makeLine();const sends=Option5.isSome(outbox)?yield*outbox.value.attach({resend:resendWith(options.dbClient,sender,storeIds,inLine),transport:sender}):withoutOutbox(sender);const{transport}=sends;const inOrder=(kind,input,intent,effect)=>{const key=recordLockKey(input.target,input.id);const annotations={"record.collection":input.collection.id,"record.id":input.id,"record.idempotency_key":input.idempotencyKey,"record.key":key,"record.target":input.target.key,"write.kind":kind};return Effect6.annotateCurrentSpan(annotations).pipe(Effect6.andThen(inLine(key,input.idempotencyKey,{queue:(after)=>sends.queue(intent(),after),unqueue:sends.unqueue(input.idempotencyKey)},writeLock().withRecord(key)(effect))),Effect6.annotateLogs(annotations))};const recordNow=(input)=>{const id=storeIds.get(recordLockKey(input.target,input.id))??input.id;return{expectedRevision:input.collection.get(id)?.revision??null,id}};const transact=Effect6.fnUntraced(function*(key,change,send){const context=yield*Effect6.context();const cancel=new AbortController;let sent;const sendOnce=async()=>settledWrite(await Effect6.runPromiseExitWith(context)(mutation(send),{signal:cancel.signal}));const transaction=options.dbClient.createTransaction({id:key,mutationFn:async()=>{sent=sendOnce();const exit=await sent;if(Exit4.isFailure(exit)){throw Cause3.squash(exit.cause)}}});const stopped=Effect6.promise(async()=>{await transaction.when("settled").catch(()=>{cancel.abort()});return await sent});yield*Effect6.try({catch:(cause)=>new RecordWriteRefused2({message:`The Record Collection refused the change: ${String(cause)}`}),try:()=>transaction.mutate(change)});const exit=yield*stopped.pipe(Effect6.onInterrupt(()=>Effect6.suspend(()=>{if(transaction.state==="persisting"){transaction.rollback()}return stopped})));if(exit===undefined){if(transaction.state==="completed"){return yield*mutation(send)}return yield*Effect6.interrupt}return yield*exit});const createRow=Effect6.fnUntraced(function*(input){const rows=yield*confirmedRowsOf(input);const row={id:input.id,revision:null,value:input.value};const lost=unanswered.get(input.idempotencyKey);const request=lost?.kind==="create"?lost.request:{id:input.id,idempotencyKey:input.idempotencyKey,target:input.target,value:input.value};const others=othersOf(options.dbClient,input,(entry)=>entry.takesCreate(row)&&entry.collection.get(input.id)===undefined);const held=lost!==undefined&&input.collection.get(input.id)!==undefined;const confirming={base:null,resent:lost!==undefined};let shown=[];return yield*transact(input.idempotencyKey,()=>{if(!held){input.collection.insert(row)}shown=showIn(others,(collection)=>{collection.insert(row)})},sendKept({kind:"create",request},transport.create(request)).pipe(Effect6.tap((answer)=>learnStoreId(storeIds,input.target,input.id,answer)),Effect6.tap((answer)=>confirmShown(shown,answer,confirming)),Effect6.flatMap((answer)=>confirm(rows,ownShowing(options.dbClient,input),answer,confirming))))});const create=Effect6.fn("RecordWrites.create")(function*(input){return yield*inOrder("create",input,()=>({kind:"create",request:{id:input.id,idempotencyKey:input.idempotencyKey,target:input.target,value:input.value}}),createRow(input))});const updateRow=Effect6.fnUntraced(function*(input){const rows=yield*confirmedRowsOf(input);const row=input.collection.get(input.id);const lost=unanswered.get(input.idempotencyKey);const request=updateRequestOf(input,row,lost);if(request===undefined){return yield*missingRow(input)}const confirming={base:request.expectedRevision,resent:lost!==undefined};const others=othersOf(options.dbClient,input,(entry)=>entry.collection.get(input.id)!==undefined);let shown=[];return yield*transact(input.idempotencyKey,()=>{if(row!==undefined){input.collection.update(input.id,(draft)=>{Object.assign(draft.value,input.change)})}shown=showIn(others,(collection)=>{collection.update(input.id,(draft)=>{Object.assign(draft.value,input.change)})})},sendKept({kind:"update",request},transport.update(request)).pipe(Effect6.tap((answer)=>confirmShown(shown,answer,confirming)),Effect6.flatMap((answer)=>confirm(rows,ownShowing(options.dbClient,input),answer,confirming))))});const update=Effect6.fn("RecordWrites.update")(function*(input){return yield*inOrder("update",input,()=>({kind:"update",request:{...recordNow(input),change:input.change,idempotencyKey:input.idempotencyKey,target:input.target}}),Effect6.suspend(()=>atStoreId(storeIds,input,updateRow)))});const removeRow=Effect6.fnUntraced(function*(input){yield*confirmedRowsOf(input);const row=input.collection.get(input.id);const lost=unanswered.get(input.idempotencyKey);const request=deleteRequestOf(input,row,lost);if(request===undefined){return yield*missingRow(input)}const confirming={base:request.expectedRevision,resent:lost!==undefined};const others=othersOf(options.dbClient,input,(entry)=>entry.collection.get(input.id)!==undefined);const own=row===undefined?[]:[{...ownShowing(options.dbClient,input),revision:row.revision}];const revisions=new Map(others.map((entry)=>[entry.collection,entry.collection.get(input.id)?.revision??null]));let shown=[];return yield*transact(input.idempotencyKey,()=>{if(row!==undefined){input.collection.delete(input.id)}shown=showIn(others,(collection)=>{collection.delete(input.id)})},sendKept({kind:"delete",request},transport.delete(request)).pipe(Effect6.tap((answer)=>removeShown([...own,...shown.map((entry)=>({...entry,revision:revisions.get(entry.collection)??null}))],input.id,answer,confirming))))});const remove=Effect6.fn("RecordWrites.delete")(function*(input){return yield*inOrder("delete",input,()=>({kind:"delete",request:{...recordNow(input),idempotencyKey:input.idempotencyKey,target:input.target}}),Effect6.suspend(()=>atStoreId(storeIds,input,removeRow)))});return RecordWrites2.of({create,delete:remove,update})});var layer2=(options)=>Layer2.effect(RecordWrites2,make10(options));class RecordCollections2 extends Context4.Service()("@collective-intelligence/records/RecordCollections"){}var make=(options)=>Effect7.gen(function*(){const limits=options.realtimeLimits??defaultRealtimeSyncLimits;const source=yield*RealtimeChangeSource;const layerScope=yield*Effect7.scope;const syncs=yield*FiberMap.make();const runSync=yield*FiberMap.runtime(syncs)();const scopes=new Map;const open=Effect7.fnUntraced(function*(id,schema,config){const collection=options.dbClient.collection(collectionOptions({...config,id,schema:Schema11.toStandardSchemaV1(Schema11.toType(recordRowSchema(schema)))}));if(!scopes.has(id)){const scope=yield*Scope2.fork(layerScope,"sequential");yield*Scope2.addFinalizer(scope,Effect7.promise(async()=>{await collection.cleanup({dependents:true})}));scopes.set(id,scope)}return collection});const realtime=Effect7.fn("RecordCollections.realtime")(function*(topic,schema){const id=realtimeCollectionId(topic);yield*Effect7.annotateCurrentSpan({"record.collection":id});const start=makeRealtimeStart();const collection=yield*open(id,schema,{getKey:(row)=>row.id,sync:{exportSyncMeta:start.exportSyncMeta,importSyncMeta:start.importSyncMeta,rowUpdateMode:"full",sync:(sync)=>{acceptConfirmedRows(sync.collection,syncConfirmedRows(sync,schema));const fiber=runSync(id,followTopic({limits,schema,source,start,sync,topic}));return()=>{fiber.interruptUnsafe()}}}});const target=options.targetOf?.(topic);if(target!==undefined){const membership=topicMembership(topic);registerTargetCollection(options.dbClient,target,{collection,keeps:(answer)=>membership(answer)!=="out",kind:"realtime",takesCreate:(row)=>membership(row)==="in"})}return collection});const query=Effect7.fn("RecordCollections.query")(function*(queryOptions){const id=queryCollectionId(queryOptions.queryKey);yield*Effect7.annotateCurrentSpan({"record.collection":id});const context=yield*Effect7.context();const config=queryRecordCollectionOptions({context,id,options:options.identity===undefined?queryOptions:{...queryOptions,queryKey:[...recordQueryScope(options.identity),...queryOptions.queryKey]},queryClient:options.queryClient});const opened=scopes.has(id);const collection=yield*open(id,queryOptions.schema,config);if(queryOptions.target!==undefined){registerTargetCollection(options.dbClient,queryOptions.target,{collection,keeps:()=>true,kind:"query",takesCreate:()=>false})}if(opened){return collection}acceptConfirmedRows(collection,{put:async(row)=>{await config.utils.writeUpsert(row)},remove:async(rowId)=>{await config.utils.writeDelete(rowId)},schema:queryOptions.schema});return collection});return RecordCollections2.of({query,realtime})});var layer3=(options)=>Layer3.effect(RecordCollections2,make(options));
2
+ export{RecordWriteRefused2,RecordWriteConflict2,RecordWriteOutcomeUnknown2,RecordSyncFailed2,recordIdentityKey,recordQueryScope,makeRecordIdentities,realtimeCollectionId,RecordId2,RecordRevision,IdempotencyKey2,recordRowSchema,RealtimeChangeSource,RecordWriteTransport,markSeeded,RecordPosition,RealtimeSyncMeta,targetCollections,OrganizationId,UserId,outboxStorageKey,makeOutboxPage,layer,browserOutboxStorage,dropOutbox,RecordWrites2,layer2,RecordCollections2,make,layer3};