@collective-intelligence/extensions-sdk-frontend-react 0.10.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.
Files changed (48) hide show
  1. package/AGENTS.md +29 -10
  2. package/README.md +20 -21
  3. package/dist/effect/effect-runtime/query-cache.d.ts +3 -146
  4. package/dist/effect.d.ts +1 -1
  5. package/dist/effect.js +1 -1
  6. package/dist/record-layer/collection-ids.d.ts +8 -0
  7. package/dist/record-layer/collections/id-reads.d.ts +26 -0
  8. package/dist/record-layer/collections/query.d.ts +55 -0
  9. package/dist/record-layer/collections/realtime.d.ts +124 -0
  10. package/dist/record-layer/errors.d.ts +64 -0
  11. package/dist/record-layer/identity.d.ts +57 -0
  12. package/dist/record-layer/index.d.ts +23 -0
  13. package/dist/record-layer/layer.d.ts +11 -0
  14. package/dist/record-layer/machines.d.ts +45 -0
  15. package/dist/record-layer/outbox.d.ts +141 -0
  16. package/dist/record-layer/outbox.test-support.d.ts +182 -0
  17. package/dist/record-layer/ports.d.ts +141 -0
  18. package/dist/record-layer/position.d.ts +12 -0
  19. package/dist/record-layer/seed/client.d.ts +38 -0
  20. package/dist/record-layer/seed/freshness.d.ts +19 -0
  21. package/dist/record-layer/seed/server.d.ts +77 -0
  22. package/dist/record-layer/server.d.ts +6 -0
  23. package/dist/record-layer/service.d.ts +48 -0
  24. package/dist/record-layer/targets.d.ts +50 -0
  25. package/dist/record-layer/write-lock.d.ts +23 -0
  26. package/dist/record-layer/writes.d.ts +85 -0
  27. package/dist/records/adapters.d.ts +37 -0
  28. package/dist/records/runtime-provider.d.ts +22 -0
  29. package/dist/records.d.ts +12 -0
  30. package/dist/records.js +2 -0
  31. package/dist/records.server.d.ts +4 -0
  32. package/dist/records.server.js +1 -0
  33. package/dist/studio-api/@tanstack/react-query.gen.d.ts +14 -14
  34. package/dist/workflow.js +2 -1
  35. package/dist/workflows/default-template-ui/inputs/default-input-details.d.ts +9 -0
  36. package/dist/workflows/default-template-ui/inputs/translations.d.ts +5 -0
  37. package/dist/workflows/field-editor/authored-value.d.ts +4 -0
  38. package/dist/workflows/workflow-runtime/read-only-saved-value-field.d.ts +10 -0
  39. package/dist/workflows/workflow-runtime/translations.d.ts +1 -0
  40. package/docs/effect.md +8 -90
  41. package/docs/guide/ai/index.md +1 -1
  42. package/docs/guide/develop/sdks.md +10 -9
  43. package/docs/record-collections.md +147 -0
  44. package/docs/tanstack-skills.md +74 -0
  45. package/package.json +29 -7
  46. package/skills/extensions-sdk-frontend-react-move-to-record-collections/SKILL.md +54 -0
  47. package/skills/extensions-sdk-frontend-react-record-collections/SKILL.md +48 -0
  48. package/skills/extensions-sdk-frontend-react-tanstack-db-ssr/SKILL.md +34 -0
@@ -0,0 +1,12 @@
1
+ import * as Schema from "effect/Schema";
2
+ /**
3
+ * The sealed Position Token of a read: where the stream of its Realtime
4
+ * Topic starts so that it neither misses nor repeats a change after the read.
5
+ */
6
+ export declare const RecordPosition: Schema.brand<Schema.String, "RecordPosition">;
7
+ export type RecordPosition = typeof RecordPosition.Type;
8
+ /** The sync metadata of a Realtime Record Collection that loaded from a read. */
9
+ export declare const RealtimeSyncMeta: Schema.Struct<{
10
+ readonly position: Schema.brand<Schema.String, "RecordPosition">;
11
+ }>;
12
+ export type RealtimeSyncMeta = typeof RealtimeSyncMeta.Type;
@@ -0,0 +1,38 @@
1
+ import type { DbClient } from "@tanstack/db";
2
+ import type { ReactNode } from "react";
3
+ import type { RecordIdentityKey } from "../identity.js";
4
+ import type { RecordSeed } from "./server.js";
5
+ /**
6
+ * The Record Collections that an SDK provider gives its tree: the DbClient
7
+ * of its CI identity, undefined while none is signed in, and that
8
+ * identity's key, undefined for a provider without identities (Studio).
9
+ */
10
+ type RecordScope = Readonly<{
11
+ dbClient: DbClient | undefined;
12
+ identity: RecordIdentityKey | undefined;
13
+ }>;
14
+ /**
15
+ * Gives `children` the Record Collections of the provider's identity: its
16
+ * DbClient in a TanStack DB `DbProvider`, for `<RecordSeedBoundary>` and for
17
+ * TanStack DB hooks. Each SDK provider mounts it. While no identity is
18
+ * signed in, the tree has no DbClient, and a seed waits for one.
19
+ */
20
+ export declare const RecordScopeProvider: ({ children, dbClient, identity }: Readonly<{
21
+ children?: ReactNode;
22
+ } & RecordScope>) => import("react").JSX.Element;
23
+ export type RecordSeedBoundaryProps = Readonly<{
24
+ /** What `seedRecords` returned in the server render. */
25
+ seed: RecordSeed;
26
+ children?: ReactNode;
27
+ }>;
28
+ /**
29
+ * Hydrates a server seed into the browser's QueryClient and the DbClient of
30
+ * the SDK provider's identity, so the seeded rows are in the first HTML. The
31
+ * Query boundary is outside: the QueryClient holds the fetched rows before
32
+ * the DbClient applies its seed, so a Query Record Collection starts from
33
+ * them. Render it inside the SDK provider. While no identity is signed in,
34
+ * the seed waits and hydrates at the sign-in. A seed made for another CI
35
+ * identity than the provider's never hydrates, so its rows never show.
36
+ */
37
+ export declare const RecordSeedBoundary: ({ children, seed }: RecordSeedBoundaryProps) => import("react").JSX.Element;
38
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { DehydratedState, Query, QueryClient, QueryKey, StaleTime } from "@tanstack/query-core";
2
+ /**
3
+ * How long the browser takes a seeded Query as fresh after it hydrated: its
4
+ * first render reads no data again. An invalidation still refetches it.
5
+ */
6
+ export declare const seedFreshnessMillis = 60000;
7
+ /**
8
+ * Marks each Query of `state` that holds the seed's data as seeded now. Call
9
+ * it after the Query hydration of the seed.
10
+ */
11
+ export declare const markSeeded: (queryClient: QueryClient, state: DehydratedState) => void;
12
+ /**
13
+ * The stale time of a Query Record Collection's query. Until its first
14
+ * update in the browser, a seeded query stays fresh for
15
+ * `seedFreshnessMillis` after it hydrated, counted from then, so the
16
+ * server's clock does not matter. Every other query keeps the QueryClient's
17
+ * default.
18
+ */
19
+ export declare const seededStaleTime: (queryClient: QueryClient) => <Data, Failure, Key extends QueryKey>(query: Query<Data, Failure, Data, Key>) => StaleTime;
@@ -0,0 +1,77 @@
1
+ import type { DehydratedDbState } from "@tanstack/db";
2
+ import type { DehydratedState } from "@tanstack/query-core";
3
+ import { DbClient } from "@tanstack/db";
4
+ import { QueryClient } from "@tanstack/query-core";
5
+ import * as Effect from "effect/Effect";
6
+ import type { QueryRecordCollectionOptions } from "../collections/query.js";
7
+ import type { RecordIdentity, RecordIdentityKey } from "../identity.js";
8
+ import type { RecordTopic, RecordValueSchema, UndecodedRecord } from "../ports.js";
9
+ import { RecordSyncFailed } from "../errors.js";
10
+ /** The TanStack clients of one server request. */
11
+ export type RequestClients = Readonly<{
12
+ /** Holds the rows of the request's Record Collections; its `queryClient` dependency is the one below. */
13
+ dbClient: DbClient;
14
+ /** Holds the fetched rows of the request's Query Record Collections. */
15
+ queryClient: QueryClient;
16
+ }>;
17
+ /**
18
+ * The QueryClient and the `DbClient({ queryClient })` of the current server
19
+ * request: the same pair in one request, a new pair in each other request.
20
+ * Call it only in a React Server Component; React `cache()` scopes it to the
21
+ * request.
22
+ */
23
+ export declare const getRequestClients: () => RequestClients;
24
+ /** What the server read for one Realtime Record Collection. */
25
+ export type RealtimeRecordRead = Readonly<{
26
+ records: readonly UndecodedRecord[];
27
+ /**
28
+ * The `position` of the read. The browser stream of the topic starts there.
29
+ * Without one, it replays from the page's age.
30
+ */
31
+ position: string | undefined;
32
+ }>;
33
+ /** One Realtime Record Collection to seed: its topic, its value schema and its read. */
34
+ export type RealtimeRecordSeedOptions<Value extends object, E = never, R = never> = Readonly<{
35
+ topic: RecordTopic;
36
+ schema: RecordValueSchema<Value>;
37
+ load: Effect.Effect<RealtimeRecordRead, E, R>;
38
+ }>;
39
+ /**
40
+ * The Record Collections that one server render seeds. Each option names a
41
+ * collection as the browser opens it, so the seed hydrates that collection.
42
+ */
43
+ export type RecordSeedSources<E, R> = Readonly<{
44
+ /**
45
+ * The CI identity of the request's session: the application, Organization
46
+ * and user that the browser's entity source reports. The seed then keys its
47
+ * Query Record Collections as that identity's browser collections do, and
48
+ * hydrates only that identity's Record Collections. Leave it out where the
49
+ * provider has no identities (Studio).
50
+ */
51
+ identity?: RecordIdentity;
52
+ query?: readonly QueryRecordCollectionOptions<object, E, R>[];
53
+ realtime?: readonly RealtimeRecordSeedOptions<object, E, R>[];
54
+ }>;
55
+ /** The loads of one `seedRecords` call. */
56
+ export type RecordSeedLoad<Sources extends RecordSeedSources<unknown, unknown>> = NonNullable<Sources["query"]>[number]["load"] | NonNullable<Sources["realtime"]>[number]["load"];
57
+ /**
58
+ * The two payloads of a server seed. `query` holds the fetched rows of the
59
+ * Query Record Collections, `db` the rows of every seeded Record Collection,
60
+ * the live query snapshots of the first render and each Realtime Record
61
+ * Collection's position in its sync metadata.
62
+ */
63
+ export type RecordSeed = Readonly<{
64
+ query: DehydratedState;
65
+ db: DehydratedDbState;
66
+ /** The CI identity the seed was made for; only its Record Collections take it. */
67
+ identity?: RecordIdentityKey;
68
+ }>;
69
+ /**
70
+ * Fetches each Query Record Collection once into the request QueryClient
71
+ * and reads each Realtime Record Collection, renders their rows on the
72
+ * request DbClient and dehydrates both clients. A Realtime Record Collection
73
+ * is in the DB payload only, with its read's position in its sync metadata.
74
+ * Each load runs with the context of this call. Render the result in
75
+ * `<RecordSeedBoundary>`.
76
+ */
77
+ export declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
@@ -0,0 +1,6 @@
1
+ export type { QueryRecordCollectionOptions } from "./collections/query.js";
2
+ export { RecordSyncFailed } from "./errors.js";
3
+ export type { RecordIdentity } from "./identity.js";
4
+ export type { RecordTopic, RecordValueSchema, UndecodedRecord } from "./ports.js";
5
+ export type { RealtimeRecordRead, RealtimeRecordSeedOptions, RecordSeedLoad, RecordSeed, RecordSeedSources, RequestClients } from "./seed/server.js";
6
+ export { getRequestClients, seedRecords } from "./seed/server.js";
@@ -0,0 +1,48 @@
1
+ import type { DbClient } from "@tanstack/db";
2
+ import type { QueryClient } from "@tanstack/react-query";
3
+ import * as Context from "effect/Context";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Layer from "effect/Layer";
6
+ import * as Scope from "effect/Scope";
7
+ import type { QueryRecordCollection, QueryRecordCollectionOptions } from "./collections/query.js";
8
+ import type { RealtimeRecordCollection, RealtimeSyncLimits } from "./collections/realtime.js";
9
+ import type { RecordIdentityKey } from "./identity.js";
10
+ import type { RecordRow, RecordTopic, RecordValueSchema, RecordWriteTarget } from "./ports.js";
11
+ import { RealtimeChangeSource } from "./ports.js";
12
+ export type { QueryRecordCollectionOptions } from "./collections/query.js";
13
+ export type { RecordValueSchema } from "./ports.js";
14
+ export interface RecordCollectionsValue {
15
+ /** The Realtime Record Collection of one Realtime Topic. */
16
+ readonly realtime: <Value extends object>(topic: RecordTopic, schema: RecordValueSchema<Value>) => Effect.Effect<RealtimeRecordCollection<RecordRow<Value>>>;
17
+ /**
18
+ * The Query Record Collection of one query on the app's shared QueryClient.
19
+ * Its `load` runs with the context of this call, so it may need services.
20
+ */
21
+ readonly query: <Value extends object, E = never, R = never>(options: QueryRecordCollectionOptions<Value, E, R>) => Effect.Effect<QueryRecordCollection<RecordRow<Value>>, never, R>;
22
+ }
23
+ declare const RecordCollections_base: Context.ServiceClass<RecordCollections, "@collective-intelligence/records/RecordCollections", RecordCollectionsValue>;
24
+ /** The Record Collections of one CI identity. */
25
+ export declare class RecordCollections extends RecordCollections_base {
26
+ }
27
+ export type RecordCollectionsOptions = Readonly<{
28
+ /** The DbClient of one CI identity; its owner cleans it up. */
29
+ dbClient: DbClient;
30
+ /** The app's shared QueryClient, which holds the rows of Query Record Collections. */
31
+ queryClient: QueryClient;
32
+ /**
33
+ * The CI identity whose collections these are. Its key starts the Query key
34
+ * of each Query Record Collection, so identities never share Query data.
35
+ */
36
+ identity?: RecordIdentityKey | undefined;
37
+ /** How Realtime Record Collections group their Change Hints; the defaults suit an app. */
38
+ realtimeLimits?: RealtimeSyncLimits;
39
+ /**
40
+ * The write target whose records a Realtime Topic holds, if the SDK knows
41
+ * one: a record write of that target then shows in the topic's Realtime
42
+ * Record Collection too.
43
+ */
44
+ targetOf?: (topic: RecordTopic) => RecordWriteTarget | undefined;
45
+ }>;
46
+ export declare const make: (options: RecordCollectionsOptions) => Effect.Effect<RecordCollectionsValue, never, RealtimeChangeSource | Scope.Scope>;
47
+ /** `RecordCollections` over one CI identity's DbClient and the app's QueryClient. */
48
+ export declare const layer: (options: RecordCollectionsOptions) => Layer.Layer<RecordCollections, never, RealtimeChangeSource>;
@@ -0,0 +1,50 @@
1
+ import type { DbClient } from "@tanstack/db";
2
+ import type { RecordRow, RecordTopic, RecordWriteAnswer, RecordWriteTarget } from "./ports.js";
3
+ import type { RecordCollection } from "./writes.js";
4
+ /** One Record Collection that shows the records of a write target. */
5
+ export type TargetCollection = Readonly<{
6
+ collection: RecordCollection<object>;
7
+ /** A Realtime Record Collection follows CI's Change Hints; a Query Record Collection its reads. */
8
+ kind: "query" | "realtime";
9
+ /** Whether a new record `row` belongs in the collection. */
10
+ takesCreate: (row: RecordRow<object>) => boolean;
11
+ /**
12
+ * Whether the collection keeps a record it holds once CI confirmed it
13
+ * with `answer`, whose value the collection's schema has not decoded. A
14
+ * Realtime Record Collection removes only the rows that its topic filter
15
+ * surely does not match: CI sends no later Change Hint for a row outside
16
+ * the filter.
17
+ */
18
+ keeps: (answer: RecordWriteAnswer) => boolean;
19
+ }>;
20
+ /**
21
+ * Notes that `entry.collection` shows the records of `target`, so a record
22
+ * write of the target shows in it too. Opening the collection again keeps
23
+ * one entry.
24
+ */
25
+ export declare const registerTargetCollection: <Value extends object>(dbClient: DbClient, target: RecordWriteTarget, registered: Omit<TargetCollection, "collection"> & Readonly<{
26
+ collection: RecordCollection<Value>;
27
+ }>) => void;
28
+ /**
29
+ * The open Record Collections of `dbClient` that show the records of
30
+ * `target`, Realtime Record Collections first: they follow CI's Change
31
+ * Hints, so their revisions are the newest.
32
+ */
33
+ export declare const targetCollections: (dbClient: DbClient, target: RecordWriteTarget) => readonly TargetCollection[];
34
+ /** Whether a record value is in a topic: `unknown` when the value cannot tell. */
35
+ export type TopicMembership = "in" | "out" | "unknown";
36
+ /**
37
+ * Whether a record value, as the Entity API sends it, is in the topic, by
38
+ * the hub's filter rule (`passesFilter`). A relation field holds its ids
39
+ * under its key: a many field is in the topic when any id equals the filter
40
+ * value. A field with a dot is a path into the data: relation field keys
41
+ * hold no dot. Every other value compares with `===`.
42
+ *
43
+ * The value cannot tell a data array from a many relation field, so an
44
+ * array that holds the filter value is in. A path that the value does not
45
+ * hold is `unknown`: the Entity API may leave out a field that the hub
46
+ * reads. A caller keeps what it holds on `unknown` and lets CI's `leave`
47
+ * decide. The topic filter cases of the testing package pin this rule to
48
+ * the hub's.
49
+ */
50
+ export declare const topicMembership: (topic: RecordTopic) => (record: Pick<RecordWriteAnswer, "value">) => TopicMembership;
@@ -0,0 +1,23 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as Schema from "effect/Schema";
3
+ import type { RecordId, RecordWriteTarget } from "./ports.js";
4
+ /**
5
+ * The `globalThis` key of the one write lock registry, so separately bundled
6
+ * copies of the record layer serialize writes to one record (P26).
7
+ */
8
+ export declare const writeLockRegistryKey: unique symbol;
9
+ /** The key of one record's write lock: its write target and its id. */
10
+ export declare const RecordLockKey: Schema.brand<Schema.String, "RecordLockKey">;
11
+ export type RecordLockKey = typeof RecordLockKey.Type;
12
+ /** The lock key of the record `id` at `target`; equal in every bundled copy. */
13
+ export declare const recordLockKey: (target: RecordWriteTarget, id: RecordId) => RecordLockKey;
14
+ /** The registry that every bundled copy of the record layer finds on `globalThis`. */
15
+ export interface WriteLockRegistry {
16
+ /**
17
+ * Runs `self` while it holds the one permit of `key`. Writes to one key
18
+ * run in call order; writes to other keys do not wait.
19
+ */
20
+ readonly withRecord: (key: RecordLockKey) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
21
+ }
22
+ /** The write lock registry of this window, made by the first copy that asks. */
23
+ export declare const writeLock: () => WriteLockRegistry;
@@ -0,0 +1,85 @@
1
+ import type { ChangeMessageOrDeleteKeyMessage, Collection, DbClient, SyncAppliedReceipt } from "@tanstack/db";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import type { RecordWriteError } from "./errors.js";
6
+ import type { IdempotencyKey, RecordRow, RecordWriteTarget } from "./ports.js";
7
+ import type { RecordValueSchema } from "./service.js";
8
+ import { RecordId, RecordWriteTransport } from "./ports.js";
9
+ /** A Record Collection whose rows hold values of type `Value`. */
10
+ export type RecordCollection<Value extends object> = Collection<RecordRow<Value>, string>;
11
+ /**
12
+ * How CI's confirmed rows enter one Record Collection: as sync writes, so
13
+ * they replace the optimistic state when the write settles, with no revert.
14
+ */
15
+ export type ConfirmedRows<Value extends object> = Readonly<{
16
+ /** Decodes the value of CI's answer. */
17
+ schema: RecordValueSchema<Value>;
18
+ /** Puts CI's row in place of the record's synced row. */
19
+ put: (row: RecordRow<Value>) => SyncAppliedReceipt;
20
+ /** Removes the record's synced row. */
21
+ remove: (id: RecordId) => SyncAppliedReceipt;
22
+ }>;
23
+ /** The calls of one TanStack DB sync run that write rows. */
24
+ export type SyncRowWriter<Value extends object> = Readonly<{
25
+ begin: () => void;
26
+ write: (message: ChangeMessageOrDeleteKeyMessage<RecordRow<Value>, string>) => void;
27
+ commit: () => SyncAppliedReceipt;
28
+ }>;
29
+ /**
30
+ * Lets `RecordWrites` put CI's confirmed rows into `collection`. Call it in
31
+ * each run of the collection's sync: TanStack DB starts a new run after a
32
+ * cleanup, and only the current run writes rows.
33
+ */
34
+ export declare const acceptConfirmedRows: <Value extends object>(collection: RecordCollection<Value>, rows: ConfirmedRows<Value>) => void;
35
+ /** Confirmed rows written through the calls of one sync run. */
36
+ export declare const syncConfirmedRows: <Value extends object>(sync: SyncRowWriter<Value>, schema: RecordValueSchema<Value>) => ConfirmedRows<Value>;
37
+ type RecordWriteInput<Value extends object> = Readonly<{
38
+ /**
39
+ * The collection whose row the write reads (an update or a delete sends
40
+ * its revision). Every other open Record Collection of the identity that
41
+ * shows the records of `target` shows the write too.
42
+ */
43
+ collection: RecordCollection<Value>;
44
+ target: RecordWriteTarget;
45
+ /**
46
+ * The write's identity: its TanStack DB transaction id and the key a resend
47
+ * carries. A write with the key of an earlier write whose answer stayed
48
+ * lost is that write sent again (the app's resubmit): it sends the earlier
49
+ * request as it was, whatever the row shows now.
50
+ */
51
+ idempotencyKey: IdempotencyKey;
52
+ id: RecordId;
53
+ }>;
54
+ export type RecordCreateInput<Value extends object> = RecordWriteInput<Value> & Readonly<{
55
+ value: Value;
56
+ }>;
57
+ export type RecordUpdateInput<Value extends object> = RecordWriteInput<Value> & Readonly<{
58
+ change: Partial<Value>;
59
+ }>;
60
+ export type RecordDeleteInput<Value extends object> = RecordWriteInput<Value>;
61
+ export interface RecordWritesValue {
62
+ /** Shows the new record at once and creates it in CI under the client's `id`. */
63
+ readonly create: <Value extends object>(input: RecordCreateInput<Value>) => Effect.Effect<RecordRow<Value>, RecordWriteError>;
64
+ /** Shows `change` at once and sends it with the revision of the row. */
65
+ readonly update: <Value extends object>(input: RecordUpdateInput<Value>) => Effect.Effect<RecordRow<Value>, RecordWriteError>;
66
+ /** Hides the record at once and deletes it in CI. */
67
+ readonly delete: <Value extends object>(input: RecordDeleteInput<Value>) => Effect.Effect<void, RecordWriteError>;
68
+ }
69
+ declare const RecordWrites_base: Context.ServiceClass<RecordWrites, "@collective-intelligence/records/RecordWrites", RecordWritesValue>;
70
+ /**
71
+ * Writes CI records as TanStack DB transactions on Record Collections, in
72
+ * order per record, with the confirmed row in place before the write settles.
73
+ * A refused or conflicting write fails its transaction with its typed error,
74
+ * so TanStack DB rolls back only that write.
75
+ */
76
+ export declare class RecordWrites extends RecordWrites_base {
77
+ }
78
+ export type RecordWritesOptions = Readonly<{
79
+ /** The DbClient of the CI identity whose Record Collections the writes change. */
80
+ dbClient: DbClient;
81
+ }>;
82
+ export declare const make: (options: RecordWritesOptions) => Effect.Effect<RecordWritesValue, never, RecordWriteTransport | import("effect/Scope").Scope>;
83
+ /** `RecordWrites` over the DbClient of one CI identity and the SDK's write transport. */
84
+ export declare const layer: (options: RecordWritesOptions) => Layer.Layer<RecordWrites, never, RecordWriteTransport>;
85
+ export {};
@@ -0,0 +1,37 @@
1
+ import type { RecordCollectionsOptions, RecordWriteAnswer, RecordWriteError, RecordWriteTarget } from "../record-layer/index.js";
2
+ import { RecordId, RecordSyncFailed } from "../record-layer/index.js";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import * as Stream from "effect/Stream";
6
+ import type { StudioApiValue } from "../effect/studio-api/service";
7
+ import { StudioApi } from "../effect/studio-api/service";
8
+ /** The view whose data items a write target names. */
9
+ export type StudioViewData = Readonly<{
10
+ organizationId: string;
11
+ slug: string;
12
+ viewId: string;
13
+ }>;
14
+ /**
15
+ * The write target of one view's data items: the same object for each call.
16
+ * Pass it to `RecordWrites` and to `RecordCollections.query({ target })`.
17
+ */
18
+ export declare const studioViewWriteTarget: (view: StudioViewData) => RecordWriteTarget;
19
+ /**
20
+ * `RecordWriteTransport` over the Studio API. It writes view data items,
21
+ * which the Studio API can only update.
22
+ */
23
+ export declare const makeStudioWriteTransport: (api: StudioApiValue) => Readonly<{
24
+ create: (request: import("../record-layer/index.js").RecordCreateRequest) => Effect.Effect<RecordWriteAnswer, RecordWriteError>;
25
+ update: (request: import("../record-layer/index.js").RecordUpdateRequest) => Effect.Effect<RecordWriteAnswer, RecordWriteError>;
26
+ delete: (request: import("../record-layer/index.js").RecordDeleteRequest) => Effect.Effect<RecordWriteAnswer, RecordWriteError>;
27
+ }>;
28
+ export declare const studioChangeSource: Readonly<{
29
+ changes: (topic: import("../record-layer/index.js").RecordTopic, from: Effect.Effect<import("../record-layer/index.js").RecordPosition | undefined>) => Stream.Stream<import("../record-layer/index.js").RealtimeChangeItem, RecordSyncFailed>;
30
+ read: (topic: import("../record-layer/index.js").RecordTopic, id: RecordId) => Effect.Effect<import("effect/Option").Option<import("../record-layer/index.js").UndecodedRecord>, RecordSyncFailed>;
31
+ load: (topic: import("../record-layer/index.js").RecordTopic) => Effect.Effect<Readonly<{
32
+ records: readonly import("../record-layer/index.js").UndecodedRecord[];
33
+ position: import("../record-layer/index.js").RecordPosition | undefined;
34
+ }>, RecordSyncFailed>;
35
+ }>;
36
+ /** The record layer of a Studio Widget over the Studio API that the Host binds. */
37
+ export declare const layer: (options: RecordCollectionsOptions) => Layer.Layer<import("../record-layer/index.js").RecordCollections | import("../record-layer/index.js").RecordWrites, never, StudioApi>;
@@ -0,0 +1,22 @@
1
+ import type { EffectRunner } from "@collective-intelligence/effect-xstate/actors";
2
+ import type { RecordCollections, RecordWrites } from "../record-layer/index.js";
3
+ import type { ReactNode } from "react";
4
+ import type { QueryCache } from "../effect/effect-runtime/query-cache";
5
+ /** The services of a Studio Widget's record runtime. */
6
+ export type RecordRuntimeServices = QueryCache | RecordCollections | RecordWrites;
7
+ /**
8
+ * Gives its tree an Effect runtime with the `QueryCache`, `RecordCollections`
9
+ * and `RecordWrites` over the nearest `QueryClient`; in a Studio Widget, that
10
+ * is the `QueryClient` of the Studio Host. A widget that reads or writes
11
+ * records mounts it at its root, in place of `EffectRuntimeProvider` of
12
+ * `./effect`; writes of every widget to one record still run one at a time.
13
+ * A view passes the runtime to the machines it starts, in their input. When
14
+ * the provider unmounts, it closes the runtime at the end of that task: the
15
+ * runtime's writes and sync fibers stop and every Record Collection of its
16
+ * `DbClient` is cleaned up. A Strict Mode remount in the same task keeps it.
17
+ */
18
+ export declare const RecordRuntimeProvider: ({ children }: Readonly<{
19
+ children: ReactNode;
20
+ }>) => import("react").JSX.Element;
21
+ /** The runtime of the nearest `RecordRuntimeProvider`. */
22
+ export declare const useRecordRuntime: () => EffectRunner<RecordRuntimeServices>;
@@ -0,0 +1,12 @@
1
+ import type * as RecordsServer from "./record-layer/server.js";
2
+ export { fromLiveQuery, fromTransaction, IdempotencyKey, RecordCollections, RecordId, RecordSeedBoundary, RecordSyncFailed, RecordWriteConflict, RecordWriteOutcomeUnknown, RecordWriteRefused, RecordWrites } from "./record-layer/index.js";
3
+ export type { QueryRecordCollection, RealtimeRecordCollection, RecordWriteTarget, RecordSeed, RecordSeedBoundaryProps, RecordWriteError } from "./record-layer/index.js";
4
+ export type { StudioViewData } from "./records/adapters.js";
5
+ export { studioViewWriteTarget } from "./records/adapters.js";
6
+ export type { RecordRuntimeServices } from "./records/runtime-provider.js";
7
+ export { RecordRuntimeProvider, useRecordRuntime } from "./records/runtime-provider.js";
8
+ export type { RealtimeRecordRead, RealtimeRecordSeedOptions, RecordIdentity, RecordSeedLoad, RecordSeedSources, RequestClients } from "./record-layer/server.js";
9
+ /** Server only: the QueryClient and DbClient of the current request. */
10
+ export declare const getRequestClients: typeof RecordsServer.getRequestClients;
11
+ /** Server only: fetches, renders and dehydrates the seeded Record Collections. */
12
+ export declare const seedRecords: typeof RecordsServer.seedRecords;
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ import*as mt from"effect/Cause";import*as ke from"effect/Exit";import*as b from"effect/Schema";class P extends b.TaggedError()("RecordWriteRefused",{message:b.String}){}class re extends b.TaggedError()("RecordWriteConflict",{message:b.String}){}class M extends b.TaggedError()("RecordWriteOutcomeUnknown",{cause:b.optional(b.Defect()),message:b.String}){}class H extends b.TaggedError()("RecordSyncFailed",{cause:b.optional(b.Defect()),message:b.String,retrying:b.Boolean}){}var se=(e,t,o)=>{if(t&&o.retrying){e.reportError(o);return}e.fail(o)},Rt=(e)=>ke.isFailure(e)&&mt.hasInterruptsOnly(e.cause)?ke.fail(new M({message:"The write was interrupted before its answer arrived"})):e;import*as co from"effect/Layer";import{collectionOptions as nr}from"@tanstack/db";import*as ro from"effect/Context";import*as T from"effect/Effect";import*as Qe from"effect/FiberMap";import*as no from"effect/Layer";import*as je from"effect/Schema";import*as Fe from"effect/Scope";import{hashKey as gt}from"@tanstack/query-core";var St=({filter:e,schema:t})=>`ci-records:${gt(e===void 0?["realtime",t]:["realtime",t,e.field,e.eq])}`,wt=(e)=>`ci-records:${gt(["query",...e])}`;import{queryCollectionOptions as ko}from"@tanstack/query-db-collection";import*as G from"effect/Effect";import*as We from"effect/Schema";import*as _e from"effect/Context";import*as Q from"effect/Schema";var D=Q.String.pipe(Q.brand("RecordId")),le=Q.String.pipe(Q.brand("RecordRevision")),J=Q.String.pipe(Q.brand("IdempotencyKey")),ue=(e)=>Q.Struct({id:D,revision:Q.NullOr(le),value:e});class ne extends _e.Service()("@collective-intelligence/records/RealtimeChangeSource"){}class Y extends _e.Service()("@collective-intelligence/records/RecordWriteTransport"){}var Be=new WeakMap,Et=(e,t)=>{let o=e.getQueryCache();for(let r of t.queries){let n=o.get(r.queryHash);if(n!==void 0&&!Be.has(n)&&n.state.dataUpdatedAt===r.state.dataUpdatedAt)Be.set(n,{at:Date.now(),updates:n.state.dataUpdateCount})}},ht=(e)=>(t)=>{let o=Be.get(t);if(o!==void 0&&o.updates===t.state.dataUpdateCount)return Math.max(0,o.at+60000-t.state.dataUpdatedAt);let r=e.getDefaultOptions().queries?.staleTime;if(typeof r!=="function")return r??0;return r(t)};var xt=({context:e,id:t,options:o,queryClient:r})=>{let n=We.decodeUnknownEffect(We.Array(ue(o.schema))),s=o.load.pipe(G.flatMap((d)=>n(d).pipe(G.mapError((E)=>new H({cause:E,message:`A record of the Record Collection ${t} does not decode: ${E.message}`,retrying:!1})))),G.map((d)=>[...d]),G.withSpan("RecordCollections.query.load",{attributes:{"record.collection":t}}));return ko({getKey:(d)=>d.id,id:t,queryClient:r,queryFn:async({signal:d})=>await G.runPromiseWith(e)(s,{signal:d}),queryKey:o.queryKey,staleTime:ht(r)})};import*as Ie from"effect/Array";import*as a from"effect/Effect";import{pipe as kt}from"effect/Function";import*as ee from"effect/Latch";import*as V from"effect/Option";import*as Ot from"effect/Queue";import*as _ from"effect/Ref";import*as pe from"effect/Schedule";import*as Oe from"effect/Schema";import*as h from"effect/Stream";import*as ie from"effect/SubscriptionRef";import*as fe from"effect/Schema";var Wo=fe.String.pipe(fe.brand("RecordPosition")),Ct=fe.Struct({position:Wo});import*as Z from"effect/Cache";import*as ze from"effect/Effect";import*as bt from"effect/Exit";import*as He from"effect/Option";var Io={capacity:1000,timeToLive:"1 minute"},Oo=(e,t)=>He.isSome(e)&&e.value.revision===t,vt=ze.fnUntraced(function*(e,t=Io){let o=yield*Z.makeWith(e,{capacity:t.capacity,timeToLive:(r)=>bt.isFailure(r)?0:t.timeToLive});return ze.fnUntraced(function*(r,n){let s=yield*Z.getSuccess(o,r);if(He.isSome(s)&&!Oo(s.value,n))yield*Z.invalidate(o,r);return yield*Z.get(o,r)})});var Vt={batchSize:100,batchWindow:"20 millis",queueCapacity:1000,readConcurrency:8},Je=(e)=>e._tag==="resync",Wt=pe.exponential("250 millis").pipe(pe.jittered,pe.upTo({duration:"60 seconds"})),It={_tag:"keep"},Vo={_tag:"resync",generation:void 0,reason:"first-open"},Ao=(e)=>{let t=new Map;for(let o of e)if(o._tag!=="resync")t.delete(o.id),t.set(o.id,o);return[...t.values()]},To=Oe.decodeUnknownOption(Ct),At=()=>{let e;return{exportSyncMeta:()=>e===void 0?void 0:{position:e},importSyncMeta:(t)=>{let o=To(t);if(V.isSome(o))e=o.value.position},keep:(t)=>a.sync(()=>{e=t}),position:a.sync(()=>e)}},Tt=a.fn("RecordCollections.realtime.sync")(function*({limits:e,schema:t,source:o,start:r,sync:n,topic:s}){let d=yield*ee.make(),E=yield*vt((l)=>o.read(s,l)),g=Oe.decodeUnknownEffect(ue(t)),U=yield*ie.make({count:0,generation:void 0}),p=yield*_.make(V.none()),S=yield*_.make([]),K=yield*Ot.bounded(e.queueCapacity),W=(l,f)=>a.sync(()=>{se(n,ee.isOpen(d),new H({cause:f,message:`The record ${l} of the Realtime Record Collection ${n.collection.id} could not be read or decoded`,retrying:!0}))}),j=(l)=>{if(l._tag!=="change")return a.succeed({_tag:"remove",id:l.id});if(n.collection.base.get(l.id)?.revision===l.revision)return a.succeed(It);return E(l.id,l.revision).pipe(a.retry({schedule:Wt,while:(f)=>f.retrying}),a.tapError((f)=>W(l.id,f)),a.matchEffect({onFailure:()=>a.succeed({_tag:"unread",hint:l}),onSuccess:V.match({onNone:()=>a.succeed({_tag:"remove",id:l.id}),onSome:(f)=>g(f).pipe(a.map((m)=>({_tag:"write",row:m})),a.tapError((m)=>W(l.id,m)),a.orElseSucceed(()=>It))})}))},F=(l)=>g(l).pipe(a.asSome,a.tapError((f)=>W(D.make(l.id),f)),a.orElseSucceed(V.none)),v=a.fnUntraced(function*(){let{position:l,records:f}=yield*o.load(s),m=yield*a.forEach(f,F);n.begin({snapshot:!0});for(let I of m)if(V.isSome(I))n.write({type:"insert",value:I.value});n.commit(),yield*r.keep(l)}),B=a.fn("RecordCollections.realtime.reload")(function*(l,f,m){yield*a.annotateCurrentSpan({"record.collection":n.collection.id,"record.resync.count":f.count,"record.resync.generation":l.generation??"client","record.resync.reason":l.reason,"record.resync.uncovered":m}),yield*v().pipe(a.retry({schedule:Wt,while:(I)=>I.retrying}))},a.as(!0),a.tapError((l)=>a.sync(()=>{se(n,ee.isOpen(d),l)})),a.orElseSucceed(()=>!1)),c=a.fn("RecordCollections.realtime.firstLoad")(function*(){yield*a.annotateCurrentSpan({"record.collection":n.collection.id}),yield*v()},a.as(void 0),a.catch(a.succeed)),y=(yield*r.position)===void 0&&n.collection.base.size===0?yield*c():void 0,C=a.fnUntraced(function*(l){let f=yield*ie.get(U),m=[...yield*_.getAndSet(S,[]),...l],I=kt(m,Ie.findLast(Je)),O=yield*_.get(p),w=V.orElse(I,()=>O),R=V.isSome(w)?yield*B(w.value,f,V.isSome(O)):!1;yield*_.set(p,R?V.none():w);let z=kt(m,Ie.findLastIndex(Je),V.filter(()=>R),V.match({onNone:()=>m,onSome:(N)=>m.slice(N+1)})),vo=yield*a.forEach(Ao(z),j,{concurrency:e.readConcurrency}),Ge=[],$e=[];for(let N of vo)if(N._tag==="unread")$e.push(N.hint);else if(N._tag!=="keep")Ge.push(N);if(yield*a.annotateCurrentSpan({"record.hints":l.length,"record.hints.unread":$e.length}),(yield*ie.get(U)).count!==f.count)return;if(yield*_.set(S,$e),Ge.length===0)return;n.begin();for(let N of Ge)n.write(N._tag==="write"?{type:"update",value:N.row}:{key:N.id,type:"delete"});n.commit()});yield*h.concat(y===void 0?h.empty:h.make(Vo),o.changes(s,r.position)).pipe(h.tap((l)=>Je(l)?ie.update(U,(f)=>({count:f.count+1,generation:l.generation})):a.void),h.onStart(a.andThen(ee.open(d),a.sync(()=>{if(n.markReady(),y!==void 0)se(n,!0,y)}))),h.runIntoQueue(K),a.forkScoped),yield*h.fromQueue(K).pipe(h.groupedWithin(e.batchSize,e.batchWindow),h.mapEffect(C,{concurrency:1}),h.runDrain,a.catch((l)=>a.sync(()=>{se(n,ee.isOpen(d),l)})))},a.scoped);import{DbClient as Cn}from"@tanstack/db";import{hashKey as vn}from"@tanstack/query-core";import*as qo from"effect/ManagedRuntime";import*as Ve from"effect/Schema";var kn=Ve.String.pipe(Ve.brand("RecordIdentityKey"));var qt=(e)=>["ci-records",e];import*as he from"effect/Option";import*as te from"effect/Schema";var Xe=new WeakMap,Ye=(e,t,o)=>{let r=o.collection,n={...o,collection:r},s=Xe.get(e)??new Map;Xe.set(e,s);let d=s.get(t.key)??new Map;s.set(t.key,d),d.set(n.collection,n)},Ae=(e,t)=>{let o=Xe.get(e)?.get(t.key);if(o===void 0)return[];let r=[...o.values()].filter(({collection:n})=>n.status!=="cleaned-up"&&n.status!=="error");return[...r.filter(({kind:n})=>n==="realtime"),...r.filter(({kind:n})=>n==="query")]},Ko=te.decodeUnknownOption(te.Record(te.String,te.Unknown)),Kt=(e)=>Array.isArray(e.value)?he.none():Ko(e.value),Dt=(e)=>(t)=>{let{filter:o}=e;if(o===void 0)return"in";if(he.isNone(Kt(t)))return"unknown";let r=o.field.split("."),n=t.value;for(let s of r){let d=Kt({value:n});if(he.isNone(d))return"out";if(!Object.hasOwn(d.value,s))return"unknown";n=d.value[s]}if(Array.isArray(n))return r.length===1&&n.includes(o.eq)?"in":"out";return n===o.eq?"in":"out"};import{whenSyncAccepted as _o}from"@tanstack/db";import*as ae from"effect/Cause";import*as Bt from"effect/Context";import*as i from"effect/Effect";import*as Me from"effect/Exit";import*as zt from"effect/Layer";import*as me from"effect/Option";import*as Re from"effect/Schedule";import*as ge from"effect/Schema";import{createCollection as Vn,localOnlyCollectionOptions as An,safeRandomUUID as Do}from"@tanstack/db";import{IndexedDBAdapter as qn,LocalStorageAdapter as Kn,NonRetriableError as Dn,OfflineTransactionAPI as Ln,startOfflineExecutor as Un,WebLocksLeader as Pn}from"@tanstack/offline-transactions";import*as Lt from"effect/Cause";import*as Ut from"effect/Context";import*as A from"effect/Effect";import*as Lo from"effect/Exit";import*as Uo from"effect/Layer";import*as Po from"effect/Option";import*as u from"effect/Schema";var jn=u.String.pipe(u.brand("OrganizationId")),Fn=u.String.pipe(u.brand("UserId")),Nn=u.String.pipe(u.brand("OutboxStorageKey"));var Ze=u.Struct({key:u.String}),Pt=u.optional(J),Mo=u.Struct({after:Pt,followed:u.optional(u.Boolean),key:J,write:u.Union([u.Struct({kind:u.Literal("create"),request:u.Struct({id:u.optionalKey(D),idempotencyKey:J,target:Ze,value:u.Unknown})}),u.Struct({kind:u.Literal("update"),request:u.Struct({change:u.Unknown,expectedRevision:u.NullOr(le),id:D,idempotencyKey:J,target:Ze})}),u.Struct({kind:u.Literal("delete"),request:u.Struct({expectedRevision:u.NullOr(le),id:D,idempotencyKey:J,target:Ze})})])}),Gn=u.fromJsonString(u.Struct({after:Pt,idempotencyKey:J,storedAt:u.Finite,write:Mo.fields.write})),Qo=u.Struct({id:D,revision:u.NullOr(le)}),$n=u.fromJsonString(Qo);var jo=()=>({id:Do(),writes:new Map}),_n=jo();class et extends Ut.Service()("@collective-intelligence/records/RecordOutbox"){}var Mt=(e)=>({queue:()=>A.void,transport:e,unqueue:()=>A.void});var Bn=u.is(u.Union([P,re]));import*as ye from"effect/Effect";import*as Te from"effect/RcMap";import*as qe from"effect/Schema";import*as Ke from"effect/Scope";import*as jt from"effect/Semaphore";var Qt=Symbol.for("@collective-intelligence/records/write-lock/v1"),Fo=qe.String.pipe(qe.brand("RecordLockKey")),ce=(e,t)=>Fo.make(`${e.key}#${t}`),No="30 seconds",Go=()=>{let e=ye.runSync(Te.make({idleTimeToLive:No,lookup:(t)=>jt.make(1)}).pipe(Ke.provide(Ke.makeUnsafe())));return{withRecord:(t)=>(o)=>ye.scoped(ye.flatMap(Te.get(e,t),(r)=>r.withPermit(o)))}},$o=(e)=>typeof e==="object"&&e!==null&&("withRecord"in e),De=()=>{let e=Reflect.get(globalThis,Qt);if($o(e))return e;let t=Go();return Reflect.set(globalThis,Qt,t),t};var Ht=new WeakMap,it=(e,t)=>{Ht.set(e,t)},Jt=(e,t)=>({put:(o)=>(e.begin(),e.write({type:"update",value:o}),e.commit()),remove:(o)=>(e.begin(),e.write({key:o,type:"delete"}),e.commit()),schema:t});class de extends Bt.Service()("@collective-intelligence/records/RecordWrites"){}var Ft=(e)=>new P({message:`The record ${e.id} is not in the Record Collection ${e.collection.id}`}),ct=(e)=>Ht.get(e),tt=(e)=>{let t=ct(e.collection);return t===void 0?i.die(Error(`The collection ${e.collection.id} takes no confirmed rows: its sync must call acceptConfirmedRows`)):i.succeed(t)},Xt=(e)=>{let t=_o(e);return t===!0?i.void:i.promise(async()=>{await t})},Bo=()=>!0,Yt=(e,t,o,r)=>Xt(t(r)?e.put(o):e.remove(o.id)),at=(e,t,o,r)=>{if(!r.resent)return!0;if(e.kind==="realtime"||t===void 0)return!1;return t===null||t===r.base||t===o.revision},Zt=(e)=>{let{refetch:t}=e.utils;return t===void 0?i.void:i.asVoid(i.forkDetach(i.ignore(i.tryPromise(t))))},Ue=(e,t)=>!t.resent||e.kind==="realtime"?i.void:Zt(e.collection),zo=(e,t)=>i.forEach(Ae(e,t).filter(({kind:o})=>o==="query"),({collection:o})=>Zt(o),{discard:!0}),Nt=i.fnUntraced(function*(e,t,o,r){let n=yield*ge.decodeUnknownEffect(e.schema)(o.value).pipe(i.orDie),s={id:o.id,revision:o.revision,value:n},d=t.collection.get(o.id)?.revision;if(at(t,d,o,r))yield*Yt(e,t.keeps,s,o);return yield*Ue(t,r),s}),Gt=(e,t,o)=>i.forEach(e,(r)=>{let n=ct(r.collection);if(n===void 0||!at(r,r.collection.get(t.id)?.revision,t,o))return Ue(r,o);return ge.decodeUnknownOption(n.schema)(t.value).pipe(me.match({onNone:()=>i.void,onSome:(s)=>Yt(n,r.keeps,{id:t.id,revision:t.revision,value:s},t)}),i.andThen(Ue(r,o)))},{discard:!0}),Ho=(e,t,o,r)=>i.forEach(e,(n)=>{let s=ct(n.collection),d=s===void 0||!at(n,n.revision,o,r)?i.void:Xt(s.remove(t));return i.andThen(d,Ue(n,r))},{discard:!0}),ot=(e,t)=>{let o=[];for(let r of e)try{t(r.collection),o.push(r)}catch{}return o},rt=(e,t,o)=>{let r=t.collection;return Ae(e,t.target).filter((n)=>n.collection!==r&&o(n))},nt=(e,t)=>{let o=t.collection,r=Ae(e,t.target).find((n)=>n.collection===o);return{collection:o,keeps:r?.keeps??Bo,kind:r?.kind}},$t="15 seconds",Jo=Re.exponential("250 millis").pipe(Re.jittered,Re.upTo({duration:"60 seconds"})),eo=ge.is(M),Le=(e)=>e.pipe(i.timeoutOrElse({duration:$t,orElse:()=>i.fail(new M({message:`CI did not answer the write within ${$t}`}))}),i.retry({schedule:Jo,while:eo})),_t=i.fn("RecordWrites.mutationFn")(function*(e){return yield*e}),to=(e,t,o,r)=>i.sync(()=>{if(o!==void 0&&r.id!==o)e.set(ce(t,o),r.id)}),Pe=(e,t,o)=>{let r=e.get(ce(t.target,t.id));return r===void 0?o(t):i.annotateCurrentSpan({"record.store_id":r}).pipe(i.andThen(De().withRecord(ce(t.target,r))(o({...t,id:r}))))},Xo=()=>{let e=new Map;return(t,o,r,n)=>i.suspend(()=>{let s=e.get(t);e.set(t,o);let d=s!==void 0&&r!==void 0;return(d?i.andThen(r.queue(s),n):n).pipe(i.onExit((E)=>{if(e.get(t)===o)e.delete(t);return d&&Me.isFailure(E)&&!ae.hasInterruptsOnly(E.cause)?r.unqueue:i.void}))})},Yo=(e,t,o,r)=>(n)=>{let{request:s}=n,d=ce(s.target,s.id??D.make(s.idempotencyKey)),E=i.suspend(()=>{if(n.kind==="create")return Le(t.create(n.request)).pipe(i.tap((g)=>to(o,s.target,n.request.id,g)));if(n.kind==="update")return Pe(o,n.request,(g)=>Le(t.update(g)));return Pe(o,n.request,(g)=>Le(t.delete(g)))});return r(d,s.idempotencyKey,void 0,De().withRecord(d)(E)).pipe(i.tap(()=>zo(e,s.target)),i.withSpan("RecordWrites.resend",{attributes:{"record.idempotency_key":s.idempotencyKey,"record.key":d,"write.kind":n.kind}}))},Zo=(e,t,o)=>{if(o?.kind==="update")return o.request;return t===void 0?void 0:{change:e.change,expectedRevision:t.revision,id:e.id,idempotencyKey:e.idempotencyKey,target:e.target}},er=(e,t,o)=>{if(o?.kind==="delete")return o.request;return t===void 0?void 0:{expectedRevision:t.revision,id:e.id,idempotencyKey:e.idempotencyKey,target:e.target}},tr=(e)=>Me.isFailure(e)&&(ae.hasInterruptsOnly(e.cause)||me.exists(ae.findErrorOption(e.cause),eo)),or=(e)=>i.gen(function*(){let t=yield*Y,o=new Map,r=new Map,n=(c,y)=>Le(y).pipe(i.onExit((C)=>i.sync(()=>{let l=c.request.idempotencyKey;if(tr(C))r.set(l,c);else r.delete(l)}))),s=yield*i.serviceOption(et),d=Xo(),E=me.isSome(s)?yield*s.value.attach({resend:Yo(e.dbClient,t,o,d),transport:t}):Mt(t),{transport:g}=E,U=(c,y,C,l)=>{let f=ce(y.target,y.id),m={"record.collection":y.collection.id,"record.id":y.id,"record.idempotency_key":y.idempotencyKey,"record.key":f,"record.target":y.target.key,"write.kind":c};return i.annotateCurrentSpan(m).pipe(i.andThen(d(f,y.idempotencyKey,{queue:(I)=>E.queue(C(),I),unqueue:E.unqueue(y.idempotencyKey)},De().withRecord(f)(l))),i.annotateLogs(m))},p=(c)=>{let y=o.get(ce(c.target,c.id))??c.id;return{expectedRevision:c.collection.get(y)?.revision??null,id:y}},S=i.fnUntraced(function*(c,y,C){let l=yield*i.context(),f=new AbortController,m,I=async()=>Rt(await i.runPromiseExitWith(l)(_t(C),{signal:f.signal})),O=e.dbClient.createTransaction({id:c,mutationFn:async()=>{m=I();let z=await m;if(Me.isFailure(z))throw ae.squash(z.cause)}}),w=i.promise(async()=>(await O.when("settled").catch(()=>{f.abort()}),await m));yield*i.try({catch:(z)=>new P({message:`The Record Collection refused the change: ${String(z)}`}),try:()=>O.mutate(y)});let R=yield*w.pipe(i.onInterrupt(()=>i.suspend(()=>{if(O.state==="persisting")O.rollback();return w})));if(R===void 0){if(O.state==="completed")return yield*_t(C);return yield*i.interrupt}return yield*R}),K=i.fnUntraced(function*(c){let y=yield*tt(c),C={id:c.id,revision:null,value:c.value},l=r.get(c.idempotencyKey),f=l?.kind==="create"?l.request:{id:c.id,idempotencyKey:c.idempotencyKey,target:c.target,value:c.value},m=rt(e.dbClient,c,(R)=>R.takesCreate(C)&&R.collection.get(c.id)===void 0),I=l!==void 0&&c.collection.get(c.id)!==void 0,O={base:null,resent:l!==void 0},w=[];return yield*S(c.idempotencyKey,()=>{if(!I)c.collection.insert(C);w=ot(m,(R)=>{R.insert(C)})},n({kind:"create",request:f},g.create(f)).pipe(i.tap((R)=>to(o,c.target,c.id,R)),i.tap((R)=>Gt(w,R,O)),i.flatMap((R)=>Nt(y,nt(e.dbClient,c),R,O))))}),W=i.fn("RecordWrites.create")(function*(c){return yield*U("create",c,()=>({kind:"create",request:{id:c.id,idempotencyKey:c.idempotencyKey,target:c.target,value:c.value}}),K(c))}),j=i.fnUntraced(function*(c){let y=yield*tt(c),C=c.collection.get(c.id),l=r.get(c.idempotencyKey),f=Zo(c,C,l);if(f===void 0)return yield*Ft(c);let m={base:f.expectedRevision,resent:l!==void 0},I=rt(e.dbClient,c,(w)=>w.collection.get(c.id)!==void 0),O=[];return yield*S(c.idempotencyKey,()=>{if(C!==void 0)c.collection.update(c.id,(w)=>{Object.assign(w.value,c.change)});O=ot(I,(w)=>{w.update(c.id,(R)=>{Object.assign(R.value,c.change)})})},n({kind:"update",request:f},g.update(f)).pipe(i.tap((w)=>Gt(O,w,m)),i.flatMap((w)=>Nt(y,nt(e.dbClient,c),w,m))))}),F=i.fn("RecordWrites.update")(function*(c){return yield*U("update",c,()=>({kind:"update",request:{...p(c),change:c.change,idempotencyKey:c.idempotencyKey,target:c.target}}),i.suspend(()=>Pe(o,c,j)))}),v=i.fnUntraced(function*(c){yield*tt(c);let y=c.collection.get(c.id),C=r.get(c.idempotencyKey),l=er(c,y,C);if(l===void 0)return yield*Ft(c);let f={base:l.expectedRevision,resent:C!==void 0},m=rt(e.dbClient,c,(R)=>R.collection.get(c.id)!==void 0),I=y===void 0?[]:[{...nt(e.dbClient,c),revision:y.revision}],O=new Map(m.map((R)=>[R.collection,R.collection.get(c.id)?.revision??null])),w=[];return yield*S(c.idempotencyKey,()=>{if(y!==void 0)c.collection.delete(c.id);w=ot(m,(R)=>{R.delete(c.id)})},n({kind:"delete",request:l},g.delete(l)).pipe(i.tap((R)=>Ho([...I,...w.map((z)=>({...z,revision:O.get(z.collection)??null}))],c.id,R,f))))}),B=i.fn("RecordWrites.delete")(function*(c){return yield*U("delete",c,()=>({kind:"delete",request:{...p(c),idempotencyKey:c.idempotencyKey,target:c.target}}),i.suspend(()=>Pe(o,c,v)))});return de.of({create:W,delete:B,update:F})}),oo=(e)=>zt.effect(de,or(e));class xe extends ro.Service()("@collective-intelligence/records/RecordCollections"){}var ir=(e)=>T.gen(function*(){let t=e.realtimeLimits??Vt,o=yield*ne,r=yield*T.scope,n=yield*Qe.make(),s=yield*Qe.runtime(n)(),d=new Map,E=T.fnUntraced(function*(p,S,K){let W=e.dbClient.collection(nr({...K,id:p,schema:je.toStandardSchemaV1(je.toType(ue(S)))}));if(!d.has(p)){let j=yield*Fe.fork(r,"sequential");yield*Fe.addFinalizer(j,T.promise(async()=>{await W.cleanup({dependents:!0})})),d.set(p,j)}return W}),g=T.fn("RecordCollections.realtime")(function*(p,S){let K=St(p);yield*T.annotateCurrentSpan({"record.collection":K});let W=At(),j=yield*E(K,S,{getKey:(v)=>v.id,sync:{exportSyncMeta:W.exportSyncMeta,importSyncMeta:W.importSyncMeta,rowUpdateMode:"full",sync:(v)=>{it(v.collection,Jt(v,S));let B=s(K,Tt({limits:t,schema:S,source:o,start:W,sync:v,topic:p}));return()=>{B.interruptUnsafe()}}}}),F=e.targetOf?.(p);if(F!==void 0){let v=Dt(p);Ye(e.dbClient,F,{collection:j,keeps:(B)=>v(B)!=="out",kind:"realtime",takesCreate:(B)=>v(B)==="in"})}return j}),U=T.fn("RecordCollections.query")(function*(p){let S=wt(p.queryKey);yield*T.annotateCurrentSpan({"record.collection":S});let K=yield*T.context(),W=xt({context:K,id:S,options:e.identity===void 0?p:{...p,queryKey:[...qt(e.identity),...p.queryKey]},queryClient:e.queryClient}),j=d.has(S),F=yield*E(S,p.schema,W);if(p.target!==void 0)Ye(e.dbClient,p.target,{collection:F,keeps:()=>!0,kind:"query",takesCreate:()=>!1});if(j)return F;return it(F,{put:async(v)=>{await W.utils.writeUpsert(v)},remove:async(v)=>{await W.utils.writeDelete(v)},schema:p.schema}),F});return xe.of({query:U,realtime:g})}),io=(e)=>no.effect(xe,ir(e));var dt=(e)=>co.mergeAll(io(e),oo(e));import{fromEffect as ao}from"@collective-intelligence/effect-xstate/actors";import*as k from"effect/Effect";import{createActor as ar,fromCallback as dr}from"xstate";var so=(e)=>ao((t)=>k.flatMap(k.service(de),(o)=>e(o,t))),lo=(e)=>dr(({input:t,sendBack:o})=>{let r=(d)=>{o({rows:d,type:"records.rows"})},n=ao((d)=>k.gen(function*(){let g=yield*e(d);return r(yield*k.promise(async()=>await g.toArrayWhenReady())),yield*k.acquireRelease(k.sync(()=>g.subscribeChanges(()=>{r(g.toArray)})),(U)=>k.sync(()=>{U.unsubscribe()})),yield*k.never}).pipe(k.scoped)),s=ar(n,{input:t});return s.subscribe({error:(d)=>{o({error:d,type:"records.failed"})}}),s.start(),()=>{s.stop()}});import{DbProvider as sr,useOptionalDbClient as lr}from"@tanstack/react-db";import{HydrationBoundary as ur,useQueryClient as fr}from"@tanstack/react-query";import{createContext as pr,useContext as yr,useMemo as mr,useState as Rr}from"react";import{jsx as st,jsxs as wr}from"react/jsx-runtime";var uo=pr(void 0),lt=({children:e,dbClient:t,identity:o})=>{let r=mr(()=>({dbClient:t,identity:o}),[t,o]);return st(uo.Provider,{value:r,children:st(sr,{client:t,children:e})})},gr=({dbClient:e,seed:t})=>{let o=fr(),[r,n]=Rr();if(e!==void 0&&(r?.client!==e||r.seed!==t))Et(o,t.query),e.hydrate(t.db),n({client:e,seed:t});return null},Sr=(e,t,o)=>{if(e===void 0)return t;return e.identity===o.identity?e.dbClient:void 0},fo=({children:e,seed:t})=>{let o=Sr(yr(uo),lr(),t);return wr(ur,{state:o===void 0?void 0:t.query,children:[st(gr,{dbClient:o,seed:t}),e]})};import*as L from"effect/Effect";import*as we from"effect/Layer";import*as q from"effect/Schema";import*as go from"effect/Stream";import{client as Er,studioAgentRunsGet as hr,studioAgentRunsList as xr,studioViewDataGetItem as Cr,studioViewDataSearch as br,studioViewDataSearchMembers as vr,studioViewDataUpdateItem as kr,studioWorkflowRunsGet as Wr,studioWorkflowRunsList as Ir}from"@collective-intelligence/extensions-sdk-frontend-react/studio-api";import*as Or from"effect/Config";import*as po from"effect/Context";import*as be from"effect/Effect";import*as ut from"effect/Layer";import*as X from"effect/Schema";class Ce extends X.TaggedError()("StudioApiError",{body:X.Unknown,status:X.Int}){}class Se extends X.TaggedError()("StudioApiTransportError",{cause:X.Defect()}){}class ve extends po.Service()("@collective-intelligence/extensions-sdk-frontend-react/StudioApi"){}var Vr=(e={})=>{let t=e.baseUrl===void 0?{}:{baseUrl:e.baseUrl},o=(r,n)=>be.fn(`StudioApi.${r}`)(function*(d){let E=!1,g=Er.getConfig().fetch??globalThis.fetch,U=Object.assign(async(S,K)=>(E=!0,await g(S,K)),g),p=yield*be.tryPromise({catch:(S)=>{if(E)return new Se({cause:S});throw S},try:(S)=>n(d,{...t,fetch:U,responseStyle:"fields",signal:S,throwOnError:!1})});if(p.response===void 0)return yield*new Se({cause:p.error});if(!p.response.ok)return yield*new Ce({body:p.error,status:p.response.status});return p.data});return ve.of({studioAgentRunsGet:o("studioAgentRunsGet",(r,n)=>hr({...r,...n})),studioAgentRunsList:o("studioAgentRunsList",(r,n)=>xr({...r,...n})),studioViewDataGetItem:o("studioViewDataGetItem",(r,n)=>Cr({...r,...n})),studioViewDataSearch:o("studioViewDataSearch",(r,n)=>br({...r,...n})),studioViewDataSearchMembers:o("studioViewDataSearchMembers",(r,n)=>vr({...r,...n})),studioViewDataUpdateItem:o("studioViewDataUpdateItem",(r,n)=>kr({...r,...n})),studioWorkflowRunsGet:o("studioWorkflowRunsGet",(r,n)=>Wr({...r,...n})),studioWorkflowRunsList:o("studioWorkflowRunsList",(r,n)=>Ir({...r,...n}))})},yo=(e={})=>ut.sync(ve,()=>Vr(e));var mo=new Map,Ar=/^studio-view:(?<organizationId>[^/]*)\/(?<slug>[^/]*)\/(?<viewId>[^/]*)$/u,Tr=(e)=>{let t=Ar.exec(e)?.groups;if(t===void 0)return;return{organizationId:decodeURIComponent(t.organizationId??""),slug:decodeURIComponent(t.slug??""),viewId:decodeURIComponent(t.viewId??"")}},qr=(e)=>{let t=`studio-view:${[e.organizationId,e.slug,e.viewId].map((n)=>encodeURIComponent(n)).join("/")}`,o=mo.get(t);if(o!==void 0)return o;let r={key:t};return mo.set(t,r),r},Kr=q.Record(q.String,q.Unknown),Dr=q.Struct({data:q.Struct({data:q.optional(q.Unknown),id:q.String})}),Lr=new Set([502,503,504]),Ur=(e)=>{if(e._tag==="StudioApiTransportError")return new M({cause:e.cause,message:"The answer to the write did not arrive"});let t=`The Studio API answered ${e.status}`;if(Lr.has(e.status))return new M({cause:e,message:t});return e.status===409?new re({message:t}):new P({message:t})},Ro=(e)=>L.fail(new P({message:`The Studio API cannot ${e} a view data item`})),Pr=(e)=>Y.of({create:()=>Ro("create"),delete:()=>Ro("delete"),update:(t)=>L.gen(function*(){let r=Tr(t.target.key);if(r===void 0)return yield*new P({message:`No Studio view writes the target ${t.target.key}`});let n=yield*q.decodeUnknownEffect(Kr)(t.change).pipe(L.mapError((g)=>new P({message:`A view data item change is an object: ${g.message}`}))),s=yield*e.studioViewDataUpdateItem({body:{data:n},headers:{"x-idempotency-key":t.idempotencyKey,"x-organization-id":r.organizationId},path:{instanceId:t.id,slug:r.slug,viewId:r.viewId}}).pipe(L.mapError(Ur)),d=yield*q.decodeUnknownEffect(Dr)(s).pipe(L.mapError((g)=>new M({cause:g,message:"The answer to the write is not readable"})));return{id:D.make(d.data.id),revision:null,value:d.data.data}})}),ft=new H({message:"The Studio Host gives no Change Hints: use a Query Record Collection",retrying:!1}),Mr=ne.of({changes:()=>go.fail(ft),load:()=>L.fail(ft),read:()=>L.fail(ft)}),So=(e)=>dt(e).pipe(we.provide([we.succeed(ne,Mr),we.effect(Y,L.map(L.service(ve),Pr))]));import{EffectRuntimeProvider as Gr,makeEffectRuntimeContext as $r}from"@collective-intelligence/effect-xstate/react";import{DbClient as _r}from"@tanstack/db";import{useQueryClient as Br}from"@tanstack/react-query";import*as Ne from"effect/Layer";import*as Co from"effect/ManagedRuntime";import{useContext as zr,useEffect as Hr,useMemo as Jr}from"react";import{isCancelledError as Qr,QueryObserver as jr}from"@tanstack/react-query";import*as wo from"effect/Context";import*as x from"effect/Effect";import*as oe from"effect/Exit";import{constVoid as Fr}from"effect/Function";import*as Eo from"effect/Layer";import*as pt from"effect/Schema";class yt extends wo.Service()("@collective-intelligence/extensions-sdk-frontend-react/QueryCache"){}var Nr=(e)=>{let t=async({query:r,...n},s)=>{try{return oe.succeed(await e.fetchQuery({...n,queryFn:({signal:d})=>x.runPromiseWith(s)(r,{signal:d}),retry:!1}))}catch(d){if(Qr(d))return oe.interrupt();return pt.is(Ce)(d)||pt.is(Se)(d)?oe.fail(d):oe.die(d)}},o=(r)=>x.sync(()=>new jr(e,{enabled:!1,queryKey:r}).subscribe(Fr));return yt.of({cancel:(r)=>x.promise(()=>e.cancelQueries({queryKey:r})),fetch:(r)=>x.flatMap(x.context(),(n)=>x.acquireUseRelease(o(r.queryKey),()=>x.flatten(x.promise(()=>t(r,n))),(s)=>x.sync(s))),invalidate:(r)=>x.promise(()=>e.invalidateQueries({queryKey:r})),remove:(r)=>x.sync(()=>{e.removeQueries({queryKey:r})}),setData:(r,n)=>x.sync(()=>{e.setQueryData(r,n)}),update:(r,n)=>x.sync(()=>{e.setQueriesData({queryKey:r},n)})})},ho=(e)=>Eo.succeed(yt,Nr(e));import{jsx as xo}from"react/jsx-runtime";var bo=$r(),Xr=(e,t)=>Ne.mergeAll(ho(e),So({dbClient:t,queryClient:e}).pipe(Ne.provide(yo()))),Yr=async({dbClient:e,runtime:t})=>{await t.dispose(),await e.cleanup()},Ee=new WeakMap,Zr=(e)=>(Ee.set(e,(Ee.get(e)??0)+1),()=>{Ee.set(e,(Ee.get(e)??1)-1),queueMicrotask(()=>{if(Ee.get(e)===0)Ee.delete(e),Yr(e)})}),en=({children:e})=>{let t=Br(),o=Jr(()=>{let s=new _r;return{dbClient:s,runtime:Co.make(Xr(t,s))}},[t]);Hr(()=>Zr(o),[o]);let{dbClient:r,runtime:n}=o;return xo(Gr,{context:bo,runtime:n,children:xo(lt,{dbClient:r,identity:void 0,children:e})})},tn=()=>{let e=zr(bo);if(e===null)throw Error("useRecordRuntime requires a RecordRuntimeProvider");return e};export{J as IdempotencyKey,xe as RecordCollections,D as RecordId,en as RecordRuntimeProvider,fo as RecordSeedBoundary,H as RecordSyncFailed,re as RecordWriteConflict,M as RecordWriteOutcomeUnknown,P as RecordWriteRefused,de as RecordWrites,lo as fromLiveQuery,so as fromTransaction,qr as studioViewWriteTarget,tn as useRecordRuntime};
@@ -0,0 +1,4 @@
1
+ export type { RecordSeedBoundaryProps } from "./records.js";
2
+ export { RecordSeedBoundary } from "./records.js";
3
+ export type { QueryRecordCollectionOptions, RealtimeRecordRead, RealtimeRecordSeedOptions, RecordSeedLoad, RecordSeed, RecordSeedSources, RecordTopic, RecordValueSchema, RequestClients, UndecodedRecord } from "./record-layer/server.js";
4
+ export { getRequestClients, RecordSyncFailed, seedRecords } from "./record-layer/server.js";
@@ -0,0 +1 @@
1
+ import*as Ze from"effect/Cause";import*as we from"effect/Exit";import*as y from"effect/Schema";class be extends y.TaggedError()("RecordWriteRefused",{message:y.String}){}class et extends y.TaggedError()("RecordWriteConflict",{message:y.String}){}class le extends y.TaggedError()("RecordWriteOutcomeUnknown",{cause:y.optional(y.Defect()),message:y.String}){}class V extends y.TaggedError()("RecordSyncFailed",{cause:y.optional(y.Defect()),message:y.String,retrying:y.Boolean}){}var N=(e,t,o)=>{if(t&&o.retrying){e.reportError(o);return}e.fail(o)};import{collectionOptions as It,DbClient as Vt}from"@tanstack/db";import{dehydrate as Wt,QueryClient as Ot}from"@tanstack/query-core";import*as a from"effect/Effect";import*as v from"effect/Schema";import*as ne from"effect/Scope";import*as He from"effect/Stream";import{cache as Tt}from"react";import{hashKey as ve}from"@tanstack/query-core";var H=({filter:e,schema:t})=>`ci-records:${ve(e===void 0?["realtime",t]:["realtime",t,e.field,e.eq])}`,ke=(e)=>`ci-records:${ve(["query",...e])}`;import{DbClient as Lt}from"@tanstack/db";import{hashKey as tt}from"@tanstack/query-core";import*as ot from"effect/ManagedRuntime";import*as G from"effect/Schema";var rt=G.String.pipe(G.brand("RecordIdentityKey")),Ie=(e)=>rt.make(tt([e.applicationId,e.organizationId,e.userId])),J=(e)=>["ci-records",e];import*as fe from"effect/Context";import*as b from"effect/Schema";var ue=b.String.pipe(b.brand("RecordId")),nt=b.String.pipe(b.brand("RecordRevision")),Pt=b.String.pipe(b.brand("IdempotencyKey")),K=(e)=>b.Struct({id:ue,revision:b.NullOr(nt),value:e});class Q extends fe.Service()("@collective-intelligence/records/RealtimeChangeSource"){}class ct extends fe.Service()("@collective-intelligence/records/RecordWriteTransport"){}import*as F from"effect/Schema";var it=F.String.pipe(F.brand("RecordPosition")),X=F.Struct({position:it});import{collectionOptions as vt}from"@tanstack/db";import*as $e from"effect/Context";import*as C from"effect/Effect";import*as te from"effect/FiberMap";import*as kt from"effect/Layer";import*as oe from"effect/Schema";import*as re from"effect/Scope";import{queryCollectionOptions as at}from"@tanstack/query-db-collection";import*as W from"effect/Effect";import*as Y from"effect/Schema";var dt=new WeakMap;var Ve=(e)=>(t)=>{let o=dt.get(t);if(o!==void 0&&o.updates===t.state.dataUpdateCount)return Math.max(0,o.at+60000-t.state.dataUpdatedAt);let c=e.getDefaultOptions().queries?.staleTime;if(typeof c!=="function")return c??0;return c(t)};var We=({context:e,id:t,options:o,queryClient:c})=>{let i=Y.decodeUnknownEffect(Y.Array(K(o.schema))),f=o.load.pipe(W.flatMap((s)=>i(s).pipe(W.mapError((T)=>new V({cause:T,message:`A record of the Record Collection ${t} does not decode: ${T.message}`,retrying:!1})))),W.map((s)=>[...s]),W.withSpan("RecordCollections.query.load",{attributes:{"record.collection":t}}));return at({getKey:(s)=>s.id,id:t,queryClient:c,queryFn:async({signal:s})=>await W.runPromiseWith(e)(f,{signal:s}),queryKey:o.queryKey,staleTime:Ve(c)})};import*as Z from"effect/Array";import*as r from"effect/Effect";import{pipe as qe}from"effect/Function";import*as A from"effect/Latch";import*as h from"effect/Option";import*as Ae from"effect/Queue";import*as O from"effect/Ref";import*as P from"effect/Schedule";import*as ee from"effect/Schema";import*as u from"effect/Stream";import*as D from"effect/SubscriptionRef";import*as j from"effect/Cache";import*as pe from"effect/Effect";import*as Oe from"effect/Exit";import*as ye from"effect/Option";var st={capacity:1000,timeToLive:"1 minute"},lt=(e,t)=>ye.isSome(e)&&e.value.revision===t,Te=pe.fnUntraced(function*(e,t=st){let o=yield*j.makeWith(e,{capacity:t.capacity,timeToLive:(c)=>Oe.isFailure(c)?0:t.timeToLive});return pe.fnUntraced(function*(c,i){let f=yield*j.getSuccess(o,c);if(ye.isSome(f)&&!lt(f.value,i))yield*j.invalidate(o,c);return yield*j.get(o,c)})});var Ue={batchSize:100,batchWindow:"20 millis",queueCapacity:1000,readConcurrency:8},me=(e)=>e._tag==="resync",Ke=P.exponential("250 millis").pipe(P.jittered,P.upTo({duration:"60 seconds"})),je={_tag:"keep"},ft={_tag:"resync",generation:void 0,reason:"first-open"},ut=(e)=>{let t=new Map;for(let o of e)if(o._tag!=="resync")t.delete(o.id),t.set(o.id,o);return[...t.values()]},pt=ee.decodeUnknownOption(X),Me=()=>{let e;return{exportSyncMeta:()=>e===void 0?void 0:{position:e},importSyncMeta:(t)=>{let o=pt(t);if(h.isSome(o))e=o.value.position},keep:(t)=>r.sync(()=>{e=t}),position:r.sync(()=>e)}},De=r.fn("RecordCollections.realtime.sync")(function*({limits:e,schema:t,source:o,start:c,sync:i,topic:f}){let s=yield*A.make(),T=yield*Te((d)=>o.read(f,d)),M=ee.decodeUnknownEffect(K(t)),S=yield*D.make({count:0,generation:void 0}),l=yield*O.make(h.none()),m=yield*O.make([]),E=yield*Ae.bounded(e.queueCapacity),g=(d,p)=>r.sync(()=>{N(i,A.isOpen(s),new V({cause:p,message:`The record ${d} of the Realtime Record Collection ${i.collection.id} could not be read or decoded`,retrying:!0}))}),x=(d)=>{if(d._tag!=="change")return r.succeed({_tag:"remove",id:d.id});if(i.collection.base.get(d.id)?.revision===d.revision)return r.succeed(je);return T(d.id,d.revision).pipe(r.retry({schedule:Ke,while:(p)=>p.retrying}),r.tapError((p)=>g(d.id,p)),r.matchEffect({onFailure:()=>r.succeed({_tag:"unread",hint:d}),onSuccess:h.match({onNone:()=>r.succeed({_tag:"remove",id:d.id}),onSome:(p)=>M(p).pipe(r.map((w)=>({_tag:"write",row:w})),r.tapError((w)=>g(d.id,w)),r.orElseSucceed(()=>je))})}))},k=(d)=>M(d).pipe(r.asSome,r.tapError((p)=>g(ue.make(d.id),p)),r.orElseSucceed(h.none)),R=r.fnUntraced(function*(){let{position:d,records:p}=yield*o.load(f),w=yield*r.forEach(p,k);i.begin({snapshot:!0});for(let L of w)if(h.isSome(L))i.write({type:"insert",value:L.value});i.commit(),yield*c.keep(d)}),q=r.fn("RecordCollections.realtime.reload")(function*(d,p,w){yield*r.annotateCurrentSpan({"record.collection":i.collection.id,"record.resync.count":p.count,"record.resync.generation":d.generation??"client","record.resync.reason":d.reason,"record.resync.uncovered":w}),yield*R().pipe(r.retry({schedule:Ke,while:(L)=>L.retrying}))},r.as(!0),r.tapError((d)=>r.sync(()=>{N(i,A.isOpen(s),d)})),r.orElseSucceed(()=>!1)),ce=r.fn("RecordCollections.realtime.firstLoad")(function*(){yield*r.annotateCurrentSpan({"record.collection":i.collection.id}),yield*R()},r.as(void 0),r.catch(r.succeed)),ie=(yield*c.position)===void 0&&i.collection.base.size===0?yield*ce():void 0,Je=r.fnUntraced(function*(d){let p=yield*D.get(S),w=[...yield*O.getAndSet(m,[]),...d],L=qe(w,Z.findLast(me)),Ce=yield*O.get(l),de=h.orElse(L,()=>Ce),xe=h.isSome(de)?yield*q(de.value,p,h.isSome(Ce)):!1;yield*O.set(l,xe?h.none():de);let Xe=qe(w,Z.findLastIndex(me),h.filter(()=>xe),h.match({onNone:()=>w,onSome:(I)=>w.slice(I+1)})),Ye=yield*r.forEach(ut(Xe),x,{concurrency:e.readConcurrency}),ae=[],se=[];for(let I of Ye)if(I._tag==="unread")se.push(I.hint);else if(I._tag!=="keep")ae.push(I);if(yield*r.annotateCurrentSpan({"record.hints":d.length,"record.hints.unread":se.length}),(yield*D.get(S)).count!==p.count)return;if(yield*O.set(m,se),ae.length===0)return;i.begin();for(let I of ae)i.write(I._tag==="write"?{type:"update",value:I.row}:{key:I.id,type:"delete"});i.commit()});yield*u.concat(ie===void 0?u.empty:u.make(ft),o.changes(f,c.position)).pipe(u.tap((d)=>me(d)?D.update(S,(p)=>({count:p.count+1,generation:d.generation})):r.void),u.onStart(r.andThen(A.open(s),r.sync(()=>{if(i.markReady(),ie!==void 0)N(i,!0,ie)}))),u.runIntoQueue(E),r.forkScoped),yield*u.fromQueue(E).pipe(u.groupedWithin(e.batchSize,e.batchWindow),u.mapEffect(Je,{concurrency:1}),u.runDrain,r.catch((d)=>r.sync(()=>{N(i,A.isOpen(s),d)})))},r.scoped);import*as z from"effect/Option";import*as U from"effect/Schema";var Le=new WeakMap,Re=(e,t,o)=>{let c=o.collection,i={...o,collection:c},f=Le.get(e)??new Map;Le.set(e,f);let s=f.get(t.key)??new Map;f.set(t.key,s),s.set(i.collection,i)};var yt=U.decodeUnknownOption(U.Record(U.String,U.Unknown)),Qe=(e)=>Array.isArray(e.value)?z.none():yt(e.value),Fe=(e)=>(t)=>{let{filter:o}=e;if(o===void 0)return"in";if(z.isNone(Qe(t)))return"unknown";let c=o.field.split("."),i=t.value;for(let f of c){let s=Qe({value:i});if(z.isNone(s))return"out";if(!Object.hasOwn(s.value,f))return"unknown";i=s.value[f]}if(Array.isArray(i))return c.length===1&&i.includes(o.eq)?"in":"out";return i===o.eq?"in":"out"};import{whenSyncAccepted as mt}from"@tanstack/db";import*as Se from"effect/Cause";import*as Pe from"effect/Context";import*as n from"effect/Effect";import*as Rt from"effect/Exit";import*as St from"effect/Layer";import*as Ee from"effect/Option";import*as _ from"effect/Schedule";import*as B from"effect/Schema";var Et=new WeakMap,ge=(e,t)=>{Et.set(e,t)},_e=(e,t)=>({put:(o)=>(e.begin(),e.write({type:"update",value:o}),e.commit()),remove:(o)=>(e.begin(),e.write({key:o,type:"delete"}),e.commit()),schema:t});class gt extends Pe.Service()("@collective-intelligence/records/RecordWrites"){}var ht=(e)=>{let t=mt(e);return t===!0?n.void:n.promise(async()=>{await t})};var Ct=(e,t,o,c)=>ht(t(c)?e.put(o):e.remove(o.id)),xt=(e,t,o,c)=>{if(!c.resent)return!0;if(e.kind==="realtime"||t===void 0)return!1;return t===null||t===c.base||t===o.revision},wt=(e)=>{let{refetch:t}=e.utils;return t===void 0?n.void:n.asVoid(n.forkDetach(n.ignore(n.tryPromise(t))))},bt=(e,t)=>!t.resent||e.kind==="realtime"?n.void:wt(e.collection);var so=n.fnUntraced(function*(e,t,o,c){let i=yield*B.decodeUnknownEffect(e.schema)(o.value).pipe(n.orDie),f={id:o.id,revision:o.revision,value:i},s=t.collection.get(o.id)?.revision;if(xt(t,s,o,c))yield*Ct(e,t.keeps,f,o);return yield*bt(t,c),f});var lo=_.exponential("250 millis").pipe(_.jittered,_.upTo({duration:"60 seconds"})),fo=B.is(le);var uo=n.fn("RecordWrites.mutationFn")(function*(e){return yield*e});class Ne extends $e.Service()("@collective-intelligence/records/RecordCollections"){}var ze=(e)=>C.gen(function*(){let t=e.realtimeLimits??Ue,o=yield*Q,c=yield*C.scope,i=yield*te.make(),f=yield*te.runtime(i)(),s=new Map,T=C.fnUntraced(function*(l,m,E){let g=e.dbClient.collection(vt({...E,id:l,schema:oe.toStandardSchemaV1(oe.toType(K(m)))}));if(!s.has(l)){let x=yield*re.fork(c,"sequential");yield*re.addFinalizer(x,C.promise(async()=>{await g.cleanup({dependents:!0})})),s.set(l,x)}return g}),M=C.fn("RecordCollections.realtime")(function*(l,m){let E=H(l);yield*C.annotateCurrentSpan({"record.collection":E});let g=Me(),x=yield*T(E,m,{getKey:(R)=>R.id,sync:{exportSyncMeta:g.exportSyncMeta,importSyncMeta:g.importSyncMeta,rowUpdateMode:"full",sync:(R)=>{ge(R.collection,_e(R,m));let q=f(E,De({limits:t,schema:m,source:o,start:g,sync:R,topic:l}));return()=>{q.interruptUnsafe()}}}}),k=e.targetOf?.(l);if(k!==void 0){let R=Fe(l);Re(e.dbClient,k,{collection:x,keeps:(q)=>R(q)!=="out",kind:"realtime",takesCreate:(q)=>R(q)==="in"})}return x}),S=C.fn("RecordCollections.query")(function*(l){let m=ke(l.queryKey);yield*C.annotateCurrentSpan({"record.collection":m});let E=yield*C.context(),g=We({context:E,id:m,options:e.identity===void 0?l:{...l,queryKey:[...J(e.identity),...l.queryKey]},queryClient:e.queryClient}),x=s.has(m),k=yield*T(m,l.schema,g);if(l.target!==void 0)Re(e.dbClient,l.target,{collection:k,keeps:()=>!0,kind:"query",takesCreate:()=>!1});if(x)return k;return ge(k,{put:async(R)=>{await g.utils.writeUpsert(R)},remove:async(R)=>{await g.utils.writeDelete(R)},schema:l.schema}),k});return Ne.of({query:S,realtime:M})});var qt=Q.of({changes:()=>He.die("A server seed follows no Realtime Topic"),read:()=>a.die("A server seed reads no record by id"),load:()=>a.die("A server seed reloads no Realtime Topic")}),he=Tt(()=>{let e=new Ot;return{dbClient:new Vt({queryClient:e}),queryClient:e}}),Kt=(e,t)=>{let o=v.decodeUnknownEffect(v.Struct({meta:v.UndefinedOr(X),rows:v.Array(K(e))}));return(c)=>o({meta:c.position===void 0?void 0:{position:c.position},rows:c.records}).pipe(a.mapError((i)=>new V({cause:i,message:`The read of the Record Collection ${t} does not decode: ${i.message}`,retrying:!1})))},Be=(e,t)=>a.tryPromise({catch:(o)=>new V({cause:o,message:`The Record Collection ${t.id} could not be seeded`,retrying:!1}),try:async()=>{await e.preloadLiveQuery({query:(o)=>o.from({record:t})})}});function Ge(e){return a.gen(function*(){let{dbClient:t,queryClient:o}=he(),c=e.identity===void 0?void 0:Ie(e.identity),i=yield*ze({dbClient:t,identity:c,queryClient:o}).pipe(a.provideService(Q,qt)),f=(S)=>c===void 0?S.queryKey:[...J(c),...S.queryKey],s=a.fnUntraced(function*(S){let l=yield*i.query(S),m=yield*a.exit(Be(t,l)),E=o.getQueryState(f(S));if(E?.status==="error"&&E.error!==null)return yield*a.fail(E.error);return yield*m}),T=a.fnUntraced(function*(S){let l=H(S.topic),{meta:m,rows:E}=yield*S.load.pipe(a.flatMap(Kt(S.schema,l))),g=t.collection(It({getKey:(x)=>x.id,id:l,schema:v.toStandardSchemaV1(v.toType(K(S.schema))),sync:{exportSyncMeta:()=>m,rowUpdateMode:"full",sync:({begin:x,commit:k,markReady:R,write:q})=>{x();for(let ce of E)q({type:"insert",value:ce});k(),R()}}}));yield*Be(t,g)});yield*a.all([a.forEach(e.query??[],s,{concurrency:"unbounded",discard:!0}),a.forEach(e.realtime??[],T,{concurrency:"unbounded",discard:!0})],{concurrency:"unbounded",discard:!0});let M={db:t.dehydrate(),query:Wt(o)};return c===void 0?M:{...M,identity:c}}).pipe(a.provideServiceEffect(ne.Scope,ne.make()),a.withSpan("seedRecords"))}import{RecordSeedBoundary as Lo}from"./records.js";export{Lo as RecordSeedBoundary,V as RecordSyncFailed,he as getRequestClients,Ge as seedRecords};