@collective-intelligence/external-apps-client-sdk-react 0.13.4 → 0.13.6

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/dist/records.d.ts CHANGED
@@ -19,6 +19,8 @@ import { ReactNode } from 'react';
19
19
  import { CallbackActorLogic, PromiseActorLogic } from 'xstate';
20
20
 
21
21
  declare const RecordWriteRefused_base: Schema.Class<RecordWriteRefused, Schema.TaggedStruct<"RecordWriteRefused", {
22
+ /** Why the record layer refused the write before CI saw it, as `RecordIdentityMissing`. */
23
+ readonly cause: Schema.optional<Schema.Defect>;
22
24
  readonly message: Schema.String;
23
25
  }>, Cause.YieldableError>;
24
26
  /**
@@ -127,9 +129,33 @@ export type RecordWriteTarget = Readonly<{
127
129
  }>;
128
130
  /** A Record Collection kept fresh by the Change Hints of one Realtime Topic. */
129
131
  export type RealtimeRecordCollection<T extends object> = Collection<T, string>;
132
+ /**
133
+ * The rows that a Realtime Record Collection starts with: the records of
134
+ * one read as CI gave them, and its position.
135
+ */
136
+ export type RealtimeSeed = Readonly<{
137
+ records: readonly UndecodedRecord[];
138
+ /**
139
+ * The read's position, where the stream starts. With none, one load
140
+ * replaces the rows: a topic that joins after others caught up starts at
141
+ * the cursor, past the changes since the read.
142
+ */
143
+ position?: string | undefined;
144
+ }>;
145
+ /** How `RecordCollections.realtime` opens a collection that is not open yet. */
146
+ export type RealtimeRecordCollectionOptions = Readonly<{
147
+ /** * The rows to start with, from a read the app already made: the
148
+ * collection is ready with them. With a position it makes no first load
149
+ * and starts its stream there; with none, one load replaces the rows.
150
+ */
151
+ seed?: RealtimeSeed | undefined;
152
+ }>;
130
153
  export interface RecordCollectionsValue {
131
- /** The Realtime Record Collection of one Realtime Topic. */
132
- readonly realtime: <Value extends object>(topic: RecordTopic, schema: RecordValueSchema<Value>) => Effect.Effect<RealtimeRecordCollection<RecordRow<Value>>>;
154
+ /**
155
+ * The Realtime Record Collection of one Realtime Topic. A collection that
156
+ * is already open ignores `options`: the open collection wins.
157
+ */
158
+ readonly realtime: <Value extends object>(topic: RecordTopic, schema: RecordValueSchema<Value>, options?: RealtimeRecordCollectionOptions) => Effect.Effect<RealtimeRecordCollection<RecordRow<Value>>>;
133
159
  /**
134
160
  * The Query Record Collection of one query on the app's shared QueryClient.
135
161
  * Its `load` runs with the context of this call, so it may need services.
@@ -300,23 +326,28 @@ export type RecordSeed = Readonly<{
300
326
  db: DehydratedDbState;
301
327
  /** The CI identity the seed was made for; only its Record Collections take it. */
302
328
  identity?: RecordIdentityKey;
329
+ /**
330
+ * The Seed Owner: the CI identity whose rows the seed holds, as ids. A seed
331
+ * boundary can open this identity's scope before the provider knows its
332
+ * identity. Equal to `identity` when hashed.
333
+ */
334
+ owner?: RecordIdentity;
335
+ }>;
336
+ export type SeedRecordsOptions = Readonly<{
337
+ /** How long to wait for the reads; `SeedWait` by default. */
338
+ wait?: Duration.Input;
303
339
  }>;
304
- declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
340
+ declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources, seedOptions?: SeedRecordsOptions): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
305
341
  export type RecordSeedBoundaryProps = Readonly<{
306
- /** What `seedRecords` returned in the server render. */
307
- seed: RecordSeed;
342
+ /**
343
+ * What `seedRecords` returned in the server render, or its promise. The
344
+ * boundary reads a promise with React `use()`, so put it inside a
345
+ * `<Suspense>`; a promise of `null` gives no seed, and the collections load
346
+ * themselves.
347
+ */
348
+ seed: RecordSeed | Promise<RecordSeed | null>;
308
349
  children?: ReactNode;
309
350
  }>;
310
- /**
311
- * Hydrates a server seed into the browser's QueryClient and the DbClient of
312
- * the SDK provider's identity, so the seeded rows are in the first HTML. The
313
- * Query boundary is outside: the QueryClient holds the fetched rows before
314
- * the DbClient applies its seed, so a Query Record Collection starts from
315
- * them. Render it inside the SDK provider. While no identity is signed in,
316
- * the seed waits and hydrates at the sign-in. A seed made for another CI
317
- * identity than the provider's never hydrates, so its rows never show.
318
- */
319
- export declare const RecordSeedBoundary: ({ children, seed }: RecordSeedBoundaryProps) => import("react").JSX.Element;
320
351
  /** A Record Collection kept fresh by `queryCollectionOptions` on the app's shared QueryClient. */
321
352
  export type QueryRecordCollection<T extends object> = Collection<T, string>;
322
353
  export type QueryRecordCollectionOptions<Value extends object, E = never, R = never> = Readonly<{
@@ -331,6 +362,15 @@ export type QueryRecordCollectionOptions<Value extends object, E = never, R = ne
331
362
  */
332
363
  target?: RecordWriteTarget;
333
364
  }>;
365
+ /**
366
+ * Hydrates a server seed, or the seed of a promise, into the record scope of
367
+ * the SDK provider's identity, so the seeded rows are in the first HTML.
368
+ * It loads the record layer of the tree's QueryClient. While the provider
369
+ * does not know its identity yet, a seed that names its Seed Owner opens
370
+ * the owner's Provisional Scope there and gives it to its subtree; the
371
+ * provider adopts that scope when the identity arrives.
372
+ */
373
+ export declare const RecordSeedBoundary: ({ children, seed }: RecordSeedBoundaryProps) => import("react").JSX.Element;
334
374
  /**
335
375
  * Closes the record layer of `queryClient`: every identity scope closes
336
376
  * (their pending writes roll back; the outbox keeps the stored ones), and
@@ -339,9 +379,11 @@ export type QueryRecordCollectionOptions<Value extends object, E = never, R = ne
339
379
  export declare const disposeRecordLayer: (queryClient: QueryClient) => Promise<void>;
340
380
  /**
341
381
  * The record layer of the signed-in CI identity: a runtime with
342
- * `RecordCollections` and `RecordWrites`. Undefined while no identity is
343
- * signed in. A user switch or a sign-out closes the old identity's Record
344
- * Collections and rolls back its pending writes.
382
+ * `RecordCollections` and `RecordWrites`. Inside a `<RecordSeedBoundary>`
383
+ * that opened its Seed Owner's Provisional Scope, the runtime of that scope.
384
+ * Undefined while no identity is signed in. A user switch or a sign-out
385
+ * closes the old identity's Record Collections and rolls back its pending
386
+ * writes.
345
387
  */
346
388
  export declare const useRecordRuntime: () => RecordRuntime | undefined;
347
389
  /** What `useRecordCollection` gives: the open's status, its collection or its error, and a retry. */
@@ -369,19 +411,43 @@ export type RecordCollectionState<Collection, E> = Readonly<{
369
411
  error: E | RecordSyncFailed;
370
412
  retry: () => void;
371
413
  }>;
414
+ /**
415
+ * What the hook reads of a Record Collection: its first load, its health
416
+ * (TanStack DB's status, whether a reload runs, and the error of a failed
417
+ * first load) and its health changes.
418
+ */
419
+ export type FollowedRecordCollection = Readonly<{
420
+ preload: () => Promise<void>;
421
+ health: Readonly<{
422
+ status: string;
423
+ reloading: boolean;
424
+ error: Readonly<{
425
+ cause: unknown;
426
+ }> | null;
427
+ }>;
428
+ on: (event: "health:change", listener: () => void) => () => void;
429
+ /** The rows it holds; a seed's hydration gives rows before its first load settles. */
430
+ size?: number;
431
+ }>;
372
432
  /**
373
433
  * Opens a Record Collection on the record layer of the signed-in identity
374
434
  * and gives its status: `opening`, then `ready` with the collection once its
375
- * first rows are loaded, or `failed` with the error when the open fails or
376
- * does not end within the Open Wait. It opens again when the identity's
377
- * record layer changes (a user switch, a sign-out, a new entity source),
378
- * when `open` changes, and on `retry()`; keep `open` stable (a module
379
- * constant or `useMemo`), as an effect's dependencies. `idle` while no
380
- * identity is signed in. A view renders each status, so no open waits unseen.
435
+ * first rows are loaded, or `failed` with the error when the open fails, the
436
+ * first load fails, or the open does not settle within the Open Wait. The
437
+ * status follows the collection's own: every view of one collection moves
438
+ * together, and a `retry()` in one view loads a failed collection again for
439
+ * all of them. It opens again when the identity's record layer changes (a
440
+ * user switch, a sign-out, a new entity source), when `open` changes, and on
441
+ * `retry()`; keep `open` stable (a module constant or `useMemo`), as an
442
+ * effect's dependencies. `idle` while no identity is signed in. A view
443
+ * renders each status, so no open waits unseen.
444
+ *
445
+ * A collection that a `<RecordSeedBoundary>` seeded is `ready` with its rows
446
+ * in the same render that hydrated it, in the server render and in the
447
+ * first browser render: the hook opens it at once when the open needs no
448
+ * wait.
381
449
  */
382
- export declare const useRecordCollection: <Collection extends Readonly<{
383
- preload: () => Promise<void>;
384
- }>, E = never>(open: Effect.Effect<Collection, E, RecordCollections | RecordWrites>) => RecordCollectionState<Collection, E>;
450
+ export declare const useRecordCollection: <Collection extends FollowedRecordCollection, E = never>(open: Effect.Effect<Collection, E, RecordCollections | RecordWrites>) => RecordCollectionState<Collection, E>;
385
451
  /** An entity contract of any record type: the write target names one. */
386
452
  export type EntityContract = ResourceDefinition<unknown, unknown, unknown>;
387
453
  /** The write target of one entity contract: the same object for each call. */
package/dist/records.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{RecordWriteRefused2,RecordWriteConflict2,RecordWriteOutcomeUnknown2,RecordSyncFailed2,RecordOutboxUnavailable2,RecordIdentityMissing2,RecordIdentityMismatch2,RecordId2,IdempotencyKey2,markSeeded,OpenWait,RecordWrites2,RecordCollections2}from"./index-4ffh8knd.js";import{entityWriteTarget2,entityTopic2,recordLayerOf,disposeRecordLayer2}from"./index-zhh7j4d6.js";import{RecordScopeContext,recordIdentityOf,useEntityRuntime}from"./index-hmgpja4s.js";import"./index-xmbt130r.js";import{fromEffect}from"@collective-intelligence/effect-xstate/actors";import*as Effect from"effect/Effect";import{createActor,fromCallback}from"xstate";var fromTransaction=(write)=>fromEffect((input)=>Effect.flatMap(Effect.service(RecordWrites2),(writes)=>write(writes,input)));var fromLiveQuery=(query)=>fromCallback(({input,sendBack})=>{const send=(rows)=>{sendBack({rows,type:"records.rows"})};const follow=fromEffect((actorInput)=>Effect.gen(function*followRows(){const rows=yield*query(actorInput);send(yield*Effect.promise(async()=>await rows.toArrayWhenReady()));yield*Effect.acquireRelease(Effect.sync(()=>rows.subscribeChanges(()=>{send(rows.toArray)})),(subscription)=>Effect.sync(()=>{subscription.unsubscribe()}));return yield*Effect.never}).pipe(Effect.scoped));const actor=createActor(follow,{input});actor.subscribe({error:(error)=>{sendBack({error,type:"records.failed"})}});actor.start();return()=>{actor.stop()}});import{useOptionalDbClient}from"@tanstack/react-db";import{HydrationBoundary as QueryHydrationBoundary,useQueryClient}from"@tanstack/react-query";import{useContext,useState}from"react";import{jsx,jsxs}from"react/jsx-runtime";var Seed=({dbClient,seed})=>{const queryClient=useQueryClient();const[hydrated,setHydrated]=useState();if(dbClient!==undefined&&(hydrated?.client!==dbClient||hydrated.seed!==seed)){markSeeded(queryClient,seed.query);dbClient.hydrate(seed.db);setHydrated({client:dbClient,seed})}return null};var seedTarget=(scope,own,seed)=>{if(scope===undefined){return own}return scope.identity===seed.identity?scope.dbClient:undefined};var RecordSeedBoundary=({children,seed})=>{const dbClient=seedTarget(useContext(RecordScopeContext),useOptionalDbClient(),seed);return jsxs(QueryHydrationBoundary,{state:dbClient===undefined?undefined:seed.query,children:[jsx(Seed,{dbClient,seed}),children]})};import{useQueryClient as useQueryClient2}from"@tanstack/react-query";import{useLayoutEffect,useSyncExternalStore}from"react";var useRecordLayer=()=>{const layer=recordLayerOf(useQueryClient2());useSyncExternalStore(layer.subscribe,layer.version,layer.version);useLayoutEffect(()=>{layer.connect()},[layer]);return layer};var useRecordRuntime=()=>{const{recordScoped,state}=useEntityRuntime();const layer=useRecordLayer();const identity=recordScoped?recordIdentityOf(state):undefined;return identity===undefined?undefined:layer.records(identity).runtime};import*as Cause from"effect/Cause";import*as Duration from"effect/Duration";import*as Effect2 from"effect/Effect";import*as Exit from"effect/Exit";import{useCallback,useEffect,useState as useState2}from"react";var failedOpen=(cause)=>new RecordSyncFailed2({cause:Cause.squash(cause),message:"The Record Collection could not open",retrying:false});var useRecordCollection=(open)=>{const runtime=useRecordRuntime();const[attempt,setAttempt]=useState2(0);const[outcome,setOutcome]=useState2();const retry=useCallback(()=>{setAttempt((value)=>value+1)},[]);useEffect(()=>{if(runtime===undefined){return}const current={attempt,open,runtime};const opening=open.pipe(Effect2.tap((collection)=>Effect2.promise(()=>collection.preload())),Effect2.timeoutOrElse({duration:OpenWait,orElse:()=>Effect2.fail(new RecordSyncFailed2({message:`The Record Collection did not open within ${Duration.format(OpenWait)}`,retrying:false}))}));const fiber=runtime.runFork(opening);fiber.addObserver((exit)=>{if(Exit.isSuccess(exit)){setOutcome({...current,collection:exit.value,status:"ready"});return}if(Cause.hasInterruptsOnly(exit.cause)){return}const failure=Cause.findErrorOption(exit.cause);setOutcome({...current,error:failure._tag==="Some"?failure.value:failedOpen(exit.cause),status:"failed"})});return()=>{fiber.interruptUnsafe()}},[runtime,open,attempt]);if(runtime===undefined){return{collection:undefined,error:undefined,retry,status:"idle"}}if(outcome===undefined||outcome.runtime!==runtime||outcome.open!==open||outcome.attempt!==attempt){return{collection:undefined,error:undefined,retry,status:"opening"}}return outcome.status==="ready"?{collection:outcome.collection,error:undefined,retry,status:"ready"}:{collection:undefined,error:outcome.error,retry,status:"failed"}};export{IdempotencyKey2 as IdempotencyKey,RecordCollections2 as RecordCollections,RecordId2 as RecordId,RecordIdentityMismatch2 as RecordIdentityMismatch,RecordIdentityMissing2 as RecordIdentityMissing,RecordOutboxUnavailable2 as RecordOutboxUnavailable,RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,RecordWriteConflict2 as RecordWriteConflict,RecordWriteOutcomeUnknown2 as RecordWriteOutcomeUnknown,RecordWriteRefused2 as RecordWriteRefused,RecordWrites2 as RecordWrites,disposeRecordLayer2 as disposeRecordLayer,entityTopic2 as entityTopic,entityWriteTarget2 as entityWriteTarget,fromLiveQuery,fromTransaction,useRecordCollection,useRecordRuntime};
2
+ import{RecordWriteRefused2,RecordWriteConflict2,RecordWriteOutcomeUnknown2,RecordSyncFailed2,RecordOutboxUnavailable2,RecordIdentityMissing2,RecordIdentityMismatch2,reportRecordLayerError,RecordId2,IdempotencyKey2,markSeeded,OpenWait,IdentityWait,RecordWrites2,RecordCollections2}from"./index-6q8fvd4x.js";import{entityWriteTarget2,entityTopic2,recordLayerOf,disposeRecordLayer2}from"./index-v9abjxx7.js";import{RecordScopeContext,RecordScopeProvider,useRecordScopeRuntime,recordIdentityOf,useEntityRuntime,useOptionalEntityRuntime}from"./index-1r3w51e7.js";import"./index-xmbt130r.js";import{fromEffect}from"@collective-intelligence/effect-xstate/actors";import*as Effect from"effect/Effect";import{createActor,fromCallback}from"xstate";var fromTransaction=(write)=>fromEffect((input)=>Effect.flatMap(Effect.service(RecordWrites2),(writes)=>write(writes,input)));var fromLiveQuery=(query)=>fromCallback(({input,sendBack})=>{const send=(rows)=>{sendBack({rows,type:"records.rows"})};const follow=fromEffect((actorInput)=>Effect.gen(function*followRows(){const rows=yield*query(actorInput);send(yield*Effect.promise(async()=>await rows.toArrayWhenReady()));yield*Effect.acquireRelease(Effect.sync(()=>rows.subscribeChanges(()=>{send(rows.toArray)})),(subscription)=>Effect.sync(()=>{subscription.unsubscribe()}));return yield*Effect.never}).pipe(Effect.scoped));const actor=createActor(follow,{input});actor.subscribe({error:(error)=>{sendBack({error,type:"records.failed"})}});actor.start();return()=>{actor.stop()}});import{useOptionalDbClient}from"@tanstack/react-db";import{HydrationBoundary as QueryHydrationBoundary,useQueryClient}from"@tanstack/react-query";import*as Duration from"effect/Duration";import{useContext,useEffect,useLayoutEffect,useRef,useState}from"react";import*as React from"react";var{use}=React;var useResolved=(value)=>{if(!("then"in(value??{}))){return value}if(use===undefined){throw new Error("Reading a seed promise needs React 19 (`use`)")}return use(value)};import{jsx,jsxs}from"react/jsx-runtime";var seededClients=new WeakSet;var useSeededRecordScope=()=>{const dbClient=useContext(RecordScopeContext)?.dbClient;return dbClient!==undefined&&seededClients.has(dbClient)};var useSeed=(seed)=>useResolved(seed);var Seed=({dbClient,seed})=>{const queryClient=useQueryClient();const[hydrated,setHydrated]=useState();if(dbClient!==undefined&&(hydrated?.client!==dbClient||hydrated.seed!==seed)){markSeeded(queryClient,seed.query);dbClient.hydrate(seed.db);seededClients.add(dbClient);setHydrated({client:dbClient,seed})}return null};var noSeed={provisional:undefined,target:undefined,waiting:false};var planSeed=(scope,own,seed,ended,provisional)=>{if(seed===null||ended){return noSeed}if(scope===undefined){return{...noSeed,target:own}}if(scope.identity!==undefined||seed.identity===undefined){return{...noSeed,target:scope.identity===seed.identity?scope.dbClient:undefined}}if(seed.owner===undefined||provisional===undefined){return{...noSeed,waiting:true}}if(provisional.ended(seed.owner)){return noSeed}const opened=provisional.open(seed.owner);return{provisional:opened,target:opened.dbClient,waiting:true}};var useSeedWait=(scope,provisional,seed,plan,ended,end)=>{const reported=useRef({});const owner=plan.provisional===undefined?undefined:seed?.owner;useLayoutEffect(()=>{if(owner!==undefined){provisional?.hold(owner)}},[owner,provisional]);const waitsHere=plan.waiting&&plan.provisional===undefined;useLayoutEffect(()=>{const timer=waitsHere&&seed!==null?setTimeout(()=>{end(seed)},Duration.toMillis(IdentityWait)):undefined;return()=>{clearTimeout(timer)}},[waitsHere,seed,end]);const identity=scope?.identity;useEffect(()=>{if(!ended||seed===null||reported.current.missing===seed){return}reported.current={...reported.current,missing:seed};reportRecordLayerError(new RecordIdentityMissing2({message:`A record seed waited ${Duration.format(IdentityWait)} for the provider's CI identity; its rows no longer show`}))},[ended,seed]);useEffect(()=>{if(seed?.identity===undefined||identity===undefined||identity===seed.identity||reported.current.mismatch===seed){return}reported.current={...reported.current,mismatch:seed};reportRecordLayerError(new RecordIdentityMismatch2({message:"A record seed was made for another CI identity than the provider's; its rows do not show"}))},[identity,seed])};var SeedBoundary=({children,provisional:scopes,seed:given})=>{const seed=useSeed(given);const scope=useContext(RecordScopeContext);const own=useOptionalDbClient();const[endedFor,setEndedFor]=useState();const[expiredFor,setExpiredFor]=useState();const ownerExpired=seed?.owner!==undefined&&scopes?.ended(seed.owner)===true;if(ownerExpired&&seed!==null&&expiredFor!==seed){setExpiredFor(seed)}const ended=seed!==null&&(endedFor===seed||expiredFor===seed||ownerExpired);const plan=planSeed(scope,own,seed,ended,scopes);useSeedWait(scope,scopes,seed,plan,endedFor===seed,setEndedFor);const{provisional}=plan;const content=jsxs(QueryHydrationBoundary,{state:plan.target===undefined?undefined:seed?.query,children:[seed===null?null:jsx(Seed,{dbClient:plan.target,seed}),children]});return scope===undefined?content:jsx(RecordScopeProvider,{dbClient:provisional?.dbClient??scope.dbClient,identity:provisional?.key??scope.identity,runtime:provisional?.runtime??scope.runtime,children:content})};import{useQueryClient as useQueryClient2}from"@tanstack/react-query";import{useLayoutEffect as useLayoutEffect2,useSyncExternalStore}from"react";var useRecordLayer=()=>{const layer=recordLayerOf(useQueryClient2());useSyncExternalStore(layer.subscribe,layer.version,layer.version);useLayoutEffect2(()=>{layer.connect()},[layer]);return layer};var useRecordRuntime=()=>{const{recordScoped,state}=useEntityRuntime();const layer=useRecordLayer();const provisional=useRecordScopeRuntime();const identity=recordScoped?recordIdentityOf(state):undefined;return provisional??(identity===undefined?undefined:layer.records(identity).runtime)};import{jsx as jsx2}from"react/jsx-runtime";var RecordSeedBoundary=({children,seed})=>{const entity=useOptionalEntityRuntime();const layer=useRecordLayer();const provisional=entity?.recordScoped===true?layer.provisionalFor(entity.state):undefined;return jsx2(SeedBoundary,{provisional,seed,children})};import*as Cause from"effect/Cause";import*as Duration2 from"effect/Duration";import*as Effect2 from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Schema from"effect/Schema";import{useCallback,useEffect as useEffect2,useMemo,useState as useState2,useSyncExternalStore as useSyncExternalStore2}from"react";var sameOpen=(a,b)=>a!==undefined&&a.runtime===b.runtime&&a.open===b.open&&a.attempt===b.attempt;var errorOf=(cause)=>{const failure=Cause.findErrorOption(cause);return failure._tag==="Some"?failure.value:new RecordSyncFailed2({cause:Cause.squash(cause),message:"The Record Collection could not open",retrying:false})};var loadFailed=(health)=>health.status==="error"&&!health.reloading;var isRecordSyncFailed=Schema.is(RecordSyncFailed2);var loadError=(health)=>{const cause=health.error?.cause;return isRecordSyncFailed(cause)?cause:new RecordSyncFailed2({cause,message:"The Record Collection could not load",retrying:false})};var healthHolds=(collection,holds)=>Effect2.callback((resume)=>{const check=()=>{if(holds(collection.health)){resume(Effect2.undefined)}};const stop=collection.on("health:change",check);check();return Effect2.sync(stop)});var loadSettled=(health)=>health.status==="ready"||loadFailed(health);var settled=(collection)=>Effect2.tryPromise(()=>collection.preload()).pipe(Effect2.ignore,Effect2.andThen(healthHolds(collection,loadSettled)));var withinOpenWait=(wait)=>wait.pipe(Effect2.timeoutOrElse({duration:OpenWait,orElse:()=>Effect2.fail(new RecordSyncFailed2({message:`The Record Collection did not open within ${Duration2.format(OpenWait)}`,retrying:false}))}));var holdsRows=(collection)=>collection.health.status==="ready"||(collection.size??0)>0&&!loadFailed(collection.health);var openAtOnce=(runtime,open)=>{const fiber=runtime.runFork(open);const exit=fiber.pollUnsafe();if(exit===undefined){fiber.interruptUnsafe();return}return Exit.isSuccess(exit)&&holdsRows(exit.value)?exit.value:undefined};var follow=(open,view)=>Effect2.gen(function*followOpen(){let opened;const first=yield*open.pipe(Effect2.tap((collection)=>Effect2.sync(()=>{opened=collection;view.opened(collection)})),Effect2.flatMap(settled),withinOpenWait,Effect2.exit);if(Exit.isFailure(first)){view.keepError(first.cause)}const collection=opened;if(collection===undefined){return}return yield*Effect2.forever(healthHolds(collection,(health)=>!health.reloading).pipe(Effect2.andThen(healthHolds(collection,(health)=>health.reloading)),Effect2.andThen(Effect2.sync(()=>{view.keepError()})),Effect2.andThen(withinOpenWait(healthHolds(collection,loadSettled))),Effect2.exit,Effect2.flatMap((exit)=>Exit.isFailure(exit)?Effect2.sync(()=>{view.keepError(exit.cause)}):Effect2.void)))});var useRecordCollection=(open)=>{const runtime=useRecordRuntime();const[attempt,setAttempt]=useState2(0);const[outcome,setOutcome]=useState2();const retry=useCallback(()=>{setAttempt((value)=>value+1)},[]);const seeded=useSeededRecordScope();const atOnce=useMemo(()=>runtime===undefined||!seeded?undefined:openAtOnce(runtime,open),[runtime,open,seeded]);useEffect2(()=>{if(runtime===undefined){return}const current={attempt,open,runtime};const keepError=(cause)=>{setOutcome((last)=>({...current,collection:sameOpen(last,current)?last?.collection:undefined,error:cause===undefined?undefined:errorOf(cause)}))};const following=follow(open,{keepError,opened:(collection)=>{setOutcome({...current,collection,error:undefined})}});const fiber=runtime.runFork(following);return()=>{fiber.interruptUnsafe()}},[runtime,open,attempt]);const latest=runtime!==undefined&&sameOpen(outcome,{attempt,open,runtime})?outcome:undefined;const collection=latest?.collection??(attempt===0?atOnce:undefined);const subscribe=useCallback((notify)=>collection===undefined?constVoid:collection.on("health:change",notify),[collection]);const readHealth=()=>collection?.health;const health=useSyncExternalStore2(subscribe,readHealth,readHealth);const failedLoad=useMemo(()=>health!==undefined&&loadFailed(health)?loadError(health):undefined,[health]);if(runtime===undefined){return{collection:undefined,error:undefined,retry,status:"idle"}}if(collection!==undefined&&(health?.status==="ready"||seeded&&holdsRows(collection))){return{collection,error:undefined,retry,status:"ready"}}const error=failedLoad??latest?.error;return error===undefined?{collection:undefined,error:undefined,retry,status:"opening"}:{collection:undefined,error,retry,status:"failed"}};export{IdempotencyKey2 as IdempotencyKey,RecordCollections2 as RecordCollections,RecordId2 as RecordId,RecordIdentityMismatch2 as RecordIdentityMismatch,RecordIdentityMissing2 as RecordIdentityMissing,RecordOutboxUnavailable2 as RecordOutboxUnavailable,RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,RecordWriteConflict2 as RecordWriteConflict,RecordWriteOutcomeUnknown2 as RecordWriteOutcomeUnknown,RecordWriteRefused2 as RecordWriteRefused,RecordWrites2 as RecordWrites,disposeRecordLayer2 as disposeRecordLayer,entityTopic2 as entityTopic,entityWriteTarget2 as entityWriteTarget,fromLiveQuery,fromTransaction,useRecordCollection,useRecordRuntime};
@@ -114,31 +114,38 @@ export type RecordSeed = Readonly<{
114
114
  db: DehydratedDbState;
115
115
  /** The CI identity the seed was made for; only its Record Collections take it. */
116
116
  identity?: RecordIdentityKey;
117
+ /**
118
+ * The Seed Owner: the CI identity whose rows the seed holds, as ids. A seed
119
+ * boundary can open this identity's scope before the provider knows its
120
+ * identity. Equal to `identity` when hashed.
121
+ */
122
+ owner?: RecordIdentity;
123
+ }>;
124
+ export type SeedRecordsOptions = Readonly<{
125
+ /** How long to wait for the reads; `SeedWait` by default. */
126
+ wait?: Duration.Input;
117
127
  }>;
118
128
  /**
119
129
  * Fetches each Query Record Collection once into the request QueryClient
120
130
  * and reads each Realtime Record Collection, renders their rows on the
121
131
  * request DbClient and dehydrates both clients. A Realtime Record Collection
122
132
  * is in the DB payload only, with its read's position in its sync metadata.
123
- * Each load runs with the context of this call. Render the result in
124
- * `<RecordSeedBoundary>`.
133
+ * Each load runs with the context of this call. A collection whose read does
134
+ * not answer within the Seed Wait (`seedOptions.wait`, 8 seconds by default) is
135
+ * left out of the seed, and its browser collection loads itself. Render the
136
+ * result in `<RecordSeedBoundary>`, or pass its promise to it.
125
137
  */
126
- export declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
138
+ export declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources, seedOptions?: SeedRecordsOptions): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
127
139
  export type RecordSeedBoundaryProps = Readonly<{
128
- /** What `seedRecords` returned in the server render. */
129
- seed: RecordSeed;
140
+ /**
141
+ * What `seedRecords` returned in the server render, or its promise. The
142
+ * boundary reads a promise with React `use()`, so put it inside a
143
+ * `<Suspense>`; a promise of `null` gives no seed, and the collections load
144
+ * themselves.
145
+ */
146
+ seed: RecordSeed | Promise<RecordSeed | null>;
130
147
  children?: ReactNode;
131
148
  }>;
132
- /**
133
- * Hydrates a server seed into the browser's QueryClient and the DbClient of
134
- * the SDK provider's identity, so the seeded rows are in the first HTML. The
135
- * Query boundary is outside: the QueryClient holds the fetched rows before
136
- * the DbClient applies its seed, so a Query Record Collection starts from
137
- * them. Render it inside the SDK provider. While no identity is signed in,
138
- * the seed waits and hydrates at the sign-in. A seed made for another CI
139
- * identity than the provider's never hydrates, so its rows never show.
140
- */
141
- export declare const RecordSeedBoundary: ({ children, seed }: RecordSeedBoundaryProps) => import("react").JSX.Element;
142
149
  export type QueryRecordCollectionOptions<Value extends object, E = never, R = never> = Readonly<{
143
150
  /** The key of the rows on the app's shared QueryClient. */
144
151
  queryKey: QueryKey;
@@ -151,5 +158,14 @@ export type QueryRecordCollectionOptions<Value extends object, E = never, R = ne
151
158
  */
152
159
  target?: RecordWriteTarget;
153
160
  }>;
161
+ /**
162
+ * Hydrates a server seed, or the seed of a promise, into the record scope of
163
+ * the SDK provider's identity, so the seeded rows are in the first HTML.
164
+ * It loads the record layer of the tree's QueryClient. While the provider
165
+ * does not know its identity yet, a seed that names its Seed Owner opens
166
+ * the owner's Provisional Scope there and gives it to its subtree; the
167
+ * provider adopts that scope when the identity arrives.
168
+ */
169
+ export declare const RecordSeedBoundary: ({ children, seed }: RecordSeedBoundaryProps) => import("react").JSX.Element;
154
170
 
155
171
  export {};
@@ -1 +1 @@
1
- import{RecordSyncFailed2,recordIdentityKey,recordQueryScope,realtimeCollectionId,recordRowSchema,RealtimeChangeSource,RealtimeSyncMeta,make}from"./index-4ffh8knd.js";import{collectionOptions,DbClient}from"@tanstack/db";import{dehydrate,QueryClient}from"@tanstack/query-core";import*as Effect from"effect/Effect";import*as Schema from"effect/Schema";import*as Scope from"effect/Scope";import*as Stream from"effect/Stream";import{cache}from"react";var serverChangeSource=RealtimeChangeSource.of({changes:()=>Stream.die("A server seed follows no Realtime Topic"),read:()=>Effect.die("A server seed reads no record by id"),load:()=>Effect.die("A server seed reloads no Realtime Topic")});var getRequestClients=cache(()=>{const queryClient=new QueryClient;return{dbClient:new DbClient({queryClient}),queryClient}});var decodeRead=(schema,id)=>{const decode=Schema.decodeUnknownEffect(Schema.Struct({meta:Schema.UndefinedOr(RealtimeSyncMeta),rows:Schema.Array(recordRowSchema(schema))}));return(read)=>decode({meta:read.position===undefined?undefined:{position:read.position},rows:read.records}).pipe(Effect.mapError((cause)=>new RecordSyncFailed2({cause,message:`The read of the Record Collection ${id} does not decode: ${cause.message}`,retrying:false})))};var preload=(dbClient,collection)=>Effect.tryPromise({catch:(cause)=>new RecordSyncFailed2({cause,message:`The Record Collection ${collection.id} could not be seeded`,retrying:false}),try:async()=>{await dbClient.preloadLiveQuery({query:(q)=>q.from({record:collection})})}});function seedRecords(sources){return Effect.gen(function*(){const{dbClient,queryClient}=getRequestClients();const identity=sources.identity===undefined?undefined:recordIdentityKey(sources.identity);const collections=yield*make({dbClient,identity,queryClient}).pipe(Effect.provideService(RealtimeChangeSource,serverChangeSource));const queryKeyOf=(options)=>identity===undefined?options.queryKey:[...recordQueryScope(identity),...options.queryKey];const seedQuery=Effect.fnUntraced(function*(options){const collection=yield*collections.query(options);const preloaded=yield*Effect.exit(preload(dbClient,collection));const state=queryClient.getQueryState(queryKeyOf(options));if(state?.status==="error"&&state.error!==null){return yield*Effect.fail(state.error)}return yield*preloaded});const seedRealtime=Effect.fnUntraced(function*(options){const id=realtimeCollectionId(options.topic);const{meta,rows}=yield*options.load.pipe(Effect.flatMap(decodeRead(options.schema,id)));const collection=dbClient.collection(collectionOptions({getKey:(row)=>row.id,id,schema:Schema.toStandardSchemaV1(Schema.toType(recordRowSchema(options.schema))),sync:{exportSyncMeta:()=>meta,rowUpdateMode:"full",sync:({begin,commit,markReady,write})=>{begin();for(const value of rows){write({type:"insert",value})}commit();markReady()}}}));yield*preload(dbClient,collection)});yield*Effect.all([Effect.forEach(sources.query??[],seedQuery,{concurrency:"unbounded",discard:true}),Effect.forEach(sources.realtime??[],seedRealtime,{concurrency:"unbounded",discard:true})],{concurrency:"unbounded",discard:true});const seed={db:dbClient.dehydrate(),query:dehydrate(queryClient)};return identity===undefined?seed:{...seed,identity}}).pipe(Effect.provideServiceEffect(Scope.Scope,Scope.make()),Effect.withSpan("seedRecords"))}import{RecordSeedBoundary}from"./records.js";export{RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,getRequestClients,seedRecords};
1
+ import{RecordSyncFailed2,recordIdentityKey,recordQueryScope,realtimeCollectionId,recordRowSchema,RealtimeChangeSource,RealtimeSyncMeta,SeedWait,make}from"./index-6q8fvd4x.js";import{collectionOptions,DbClient}from"@tanstack/db";import{dehydrate,QueryClient}from"@tanstack/query-core";import*as Duration from"effect/Duration";import*as Effect from"effect/Effect";import*as Option from"effect/Option";import*as Schema from"effect/Schema";import*as Scope from"effect/Scope";import*as Stream from"effect/Stream";import{cache}from"react";var serverChangeSource=RealtimeChangeSource.of({changes:()=>Stream.die("A server seed follows no Realtime Topic"),read:()=>Effect.die("A server seed reads no record by id"),load:()=>Effect.die("A server seed reloads no Realtime Topic")});var getRequestClients=cache(()=>{const queryClient=new QueryClient;return{dbClient:new DbClient({queryClient}),queryClient}});var decodeRead=(schema,id)=>{const decode=Schema.decodeUnknownEffect(Schema.Struct({meta:Schema.UndefinedOr(RealtimeSyncMeta),rows:Schema.Array(recordRowSchema(schema))}));return(read)=>decode({meta:read.position===undefined?undefined:{position:read.position},rows:read.records}).pipe(Effect.mapError((cause)=>new RecordSyncFailed2({cause,message:`The read of the Record Collection ${id} does not decode: ${cause.message}`,retrying:false})))};var preload=(dbClient,collection)=>Effect.tryPromise({catch:(cause)=>new RecordSyncFailed2({cause,message:`The Record Collection ${collection.id} could not be seeded`,retrying:false}),try:async()=>{await dbClient.preloadLiveQuery({query:(q)=>q.from({record:collection})})}});function seedRecords(sources,seedOptions){const wait=seedOptions?.wait??SeedWait;return Effect.gen(function*(){const{dbClient,queryClient}=getRequestClients();const identity=sources.identity===undefined?undefined:recordIdentityKey(sources.identity);const collections=yield*make({dbClient,identity,queryClient}).pipe(Effect.provideService(RealtimeChangeSource,serverChangeSource));const queryKeyOf=(options)=>identity===undefined?options.queryKey:[...recordQueryScope(identity),...options.queryKey];const late=new Set;const seedWait=Duration.format(Duration.fromInputUnsafe(wait));const withinSeedWait=(id,seeding)=>seeding.pipe(Effect.timeoutOption(wait),Effect.flatMap(Option.match({onNone:()=>Effect.logWarning(`The Record Collection ${id} is left out of the seed: its read did not answer within the Seed Wait (${seedWait})`).pipe(Effect.annotateLogs({"record.collection":id}),Effect.andThen(Effect.sync(()=>{late.add(id)}))),onSome:()=>Effect.void})));const seedQuery=Effect.fnUntraced(function*(options){const collection=yield*collections.query(options);const queryKey=queryKeyOf(options);yield*withinSeedWait(collection.id,Effect.gen(function*(){const preloaded=yield*Effect.exit(preload(dbClient,collection));const state=queryClient.getQueryState(queryKey);if(state?.status==="error"&&state.error!==null){return yield*Effect.fail(state.error)}return yield*preloaded}));if(late.has(collection.id)){yield*Effect.promise(async()=>{await queryClient.cancelQueries({queryKey})})}});const seedRealtime=(options)=>{const id=realtimeCollectionId(options.topic);return withinSeedWait(id,Effect.gen(function*(){const{meta,rows}=yield*options.load.pipe(Effect.flatMap(decodeRead(options.schema,id)));const collection=dbClient.collection(collectionOptions({getKey:(row)=>row.id,id,schema:Schema.toStandardSchemaV1(Schema.toType(recordRowSchema(options.schema))),sync:{exportSyncMeta:()=>meta,rowUpdateMode:"full",sync:({begin,commit,markReady,write})=>{begin();for(const value of rows){write({type:"insert",value})}commit();markReady()}}}));yield*preload(dbClient,collection)}))};yield*Effect.all([Effect.forEach(sources.query??[],seedQuery,{concurrency:"unbounded",discard:true}),Effect.forEach(sources.realtime??[],seedRealtime,{concurrency:"unbounded",discard:true})],{concurrency:"unbounded",discard:true});const seed={db:dbClient.dehydrate({shouldDehydrateCollection:(collection)=>!late.has(collection.id),shouldDehydrateLiveQuery:(query)=>query.status==="success"}),query:dehydrate(queryClient)};return sources.identity===undefined||identity===undefined?seed:{...seed,identity,owner:sources.identity}}).pipe(Effect.provideServiceEffect(Scope.Scope,Scope.make()),Effect.withSpan("seedRecords"))}import{RecordSeedBoundary}from"./records.js";export{RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,getRequestClients,seedRecords};
@@ -151,11 +151,16 @@ export type EntityIdentity = Readonly<{
151
151
  userId: string;
152
152
  organizationId: string;
153
153
  }>;
154
+ /**
155
+ * The state of an entity source. `pending`: the source does not know its
156
+ * identity yet, as in a server render or the first browser render of an app
157
+ * that learns it later; it is no sign-out.
158
+ */
154
159
  export type EntitySourceState = Readonly<{
155
160
  status: "authenticated";
156
161
  identity: EntityIdentity;
157
162
  }> | Readonly<{
158
- status: "unauthenticated" | "expired" | "forbidden";
163
+ status: "pending" | "unauthenticated" | "expired" | "forbidden";
159
164
  }>;
160
165
  /** Configured authenticated client boundary. Snapshots are stable until identity changes. */
161
166
  export interface EntitySource {
package/dist/resources.js CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,useEntityRuntime,createDelegatedEntitySource2}from"./index-hmgpja4s.js";import"./index-xmbt130r.js";import{__chunks,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-stkdxnjr.js";__chunks(import.meta.url,["j89v45dz","hmgpja4s","xmbt130r","stkdxnjr","r4wk5rcm","v0etynfj","4ffh8knd","zhh7j4d6"],[["./resources.js",1,2,3],["./index-hmgpja4s.js",2,4],["./index-xmbt130r.js"],["./index-stkdxnjr.js",1],["./index-r4wk5rcm.js"],["./entity-write-v0etynfj.js",6,7,1,2,3],["./index-4ffh8knd.js",4],["./index-zhh7j4d6.js",6,1,2,4]],0);
2
+ import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,useEntityRuntime,createDelegatedEntitySource2}from"./index-1r3w51e7.js";import"./index-xmbt130r.js";import{__chunks,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-8n0aqjh1.js";__chunks(import.meta.url,["9thsh1dw","1r3w51e7","xmbt130r","8n0aqjh1","r4wk5rcm","mkfg1nhz","6q8fvd4x","v9abjxx7"],[["./resources.js",1,2,3],["./index-1r3w51e7.js",2,4],["./index-xmbt130r.js"],["./index-8n0aqjh1.js",1],["./index-r4wk5rcm.js"],["./entity-write-mkfg1nhz.js",6,7,1,2,3],["./index-6q8fvd4x.js",4],["./index-v9abjxx7.js",6,1,2,4]],0);
3
3
  import{useMutation,useQuery,useQueryClient as useQueryClient2}from"@tanstack/react-query";import{mutationOptions}from"@tanstack/react-query";var invalidateResource=async(options)=>{await options.queryClient.invalidateQueries({queryKey:resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version)})};var createResourceMutationOptions=(options)=>mutationOptions({mutationFn:async(input)=>{let result;switch(options.operation){case"hard_delete":{unwrapResourceResult2(await options.client.hardDelete(input));break}case"restore":{result=unwrapResourceResult2(await options.client.restore(input));break}case"soft_delete":{result=unwrapResourceResult2(await options.client.softDelete(input));break}default:{throw new TypeError(`Unknown resource operation: ${String(options.operation)}`)}}return result},mutationKey:[...resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version),"mutations",options.operation],onSuccess:async()=>{await invalidateResource(options)}});import{useQueryClient}from"@tanstack/react-query";import{createContext,useContext,useEffect,useMemo,useRef}from"react";import{jsx}from"react/jsx-runtime";var useResourceQueryCleanup=(queryClient,authStatus,organizationId)=>{const previousOrganizationId=useRef(null);const input=useMemo(()=>({authStatus,organizationId}),[authStatus,organizationId]);useEffect(()=>{const previous=previousOrganizationId.current;previousOrganizationId.current=input.organizationId;if(input.authStatus!=="authenticated"){clearProtectedResourceQueries(queryClient);return}if(previous!==null&&previous!==input.organizationId){clearProtectedResourceQueries(queryClient,previous)}},[input,queryClient])};var ResourceContext=createContext(null);var ResourceProvider=({authState,capabilities,children,organizationId})=>{const queryClient=useQueryClient();useResourceQueryCleanup(queryClient,authState.status,organizationId);const value=useMemo(()=>({authState,capabilities,organizationId}),[authState,capabilities,organizationId]);return jsx(ResourceContext.Provider,{value,children})};var useResourceContext=()=>{const value=useContext(ResourceContext);if(value===null){throw new Error("ResourceProvider must wrap resource bindings")}return value};var authStateForError=(error,fallback)=>error instanceof ResourceQueryError2?mapResourceAuthState2({correlationId:error.correlationId,error:error.resourceError,ok:false}):fallback;var useResourceList=(client,query)=>{const context=useResourceContext();const result=useQuery({...createResourceListQueryOptions({client,organizationId:context.organizationId,query}),enabled:context.authState.status==="authenticated"});return{...result,authState:authStateForError(result.error,context.authState)}};var useResourceLifecycleMutation=(client,operation)=>{const{capabilities,organizationId}=useResourceContext();const queryClient=useQueryClient2();const mutation=useMutation(createResourceMutationOptions({client,operation,organizationId,queryClient}));let capability;if(operation==="hard_delete"){capability="hardDelete"}else if(operation==="soft_delete"){capability="softDelete"}else{capability=operation}return{...mutation,available:capabilities[capability]===true}};import{jsx as jsx2,jsxs,Fragment}from"react/jsx-runtime";var nextQuery=(query,result)=>{if(result.pagination==="cursor"){return result.nextCursor===undefined?undefined:{...query,pagination:{cursor:result.nextCursor,limit:query.pagination.mode==="cursor"?query.pagination.limit:25,mode:"cursor"}}}return result.page>=result.totalPages?undefined:{...query,pagination:{mode:"page",page:result.page+1,pageSize:result.pageSize}}};var previousQuery=(query,result)=>result.pagination==="page"&&result.page>1?{...query,pagination:{mode:"page",page:result.page-1,pageSize:result.pageSize}}:undefined;var DefaultStatus=({authState,error,pending})=>{let message=authState.status;if(authState.status==="authenticated"){message=pending?"Loading resources":error?.message??""}return jsx2("output",{"aria-live":"polite",children:message})};var ResourceList=({client,components,onQueryChange,query,renderItem})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{List}=components;const{Pagination}=components;const result=resourceQuery.data;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsxs(Fragment,{children:[jsx2(List,{getItemKey:(item)=>item.id,items:result.items,renderItem}),Pagination===undefined?null:jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending:resourceQuery.isFetching,onNext:()=>{if(next!==undefined){onQueryChange?.(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange?.(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})]})};var ResourceCapabilityAction=({capability,children,components,unsupported="disable"})=>{const{capabilities}=useResourceContext();const supported=capabilities[capability]===true;if(!supported&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!supported,children})};var ResourceFilter=({components,label="Search resources",onQueryChange,query})=>{const{Filter}=components;const{textSearch:_textSearch,...queryWithoutTextSearch}=query;return jsx2(Filter,{label,onChange:(value)=>{onQueryChange(value===""?queryWithoutTextSearch:{...query,textSearch:value})},value:query.textSearch??""})};var ResourcePagination=({components,isPending=false,onQueryChange,query,result})=>{const{Pagination}=components;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending,onNext:()=>{if(next!==undefined){onQueryChange(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})};var ResourceTable=({caption,client,columns,components,query})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{Table}=components;return jsx2(Table,{caption,columns,getRowKey:(row)=>row.id,renderCell:(row,column)=>column.render(row),rows:resourceQuery.data.items})};var ResourceLifecycleAction=({children,client,components,input,operation,unsupported="disable"})=>{const mutation=useResourceLifecycleMutation(client,operation);if(!mutation.available&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!mutation.available,onClick:()=>{mutation.mutate(input)},pending:mutation.isPending,children})};import{useQueryClient as useQueryClient3}from"@tanstack/react-query";import{useCallback}from"react";var useEntityChanges=(contract)=>{const runtime=useEntityRuntime();const queryClient=useQueryClient3();return useCallback((changes)=>{if(changes.length===0||!runtime.current()){return}const resourceKey=["ci-entities",...runtime.key,contract.id,contract.version];for(const change of changes){const recordKey=[...resourceKey,"record",change.id];const record=queryClient.getQueryData(recordKey);if(record?.revision!==change.revision){queryClient.invalidateQueries({exact:true,queryKey:recordKey})}}queryClient.invalidateQueries({queryKey:[...resourceKey,"list"]})},[contract.id,contract.version,queryClient,runtime])};export{EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,ResourceCapabilityAction,ResourceFilter,ResourceLifecycleAction,ResourceList,ResourcePagination,ResourceProvider,ResourceQueryError2 as ResourceQueryError,ResourceTable,createDelegatedEntitySource2 as createDelegatedEntitySource,defineEntity2 as defineEntity,hasResourceCapability2 as hasResourceCapability,mapResourceAuthState2 as mapResourceAuthState,unwrapResourceResult2 as unwrapResourceResult,useEntityChanges,useEntityCreate2 as useEntityCreate,useEntityDelete2 as useEntityDelete,useEntityList2 as useEntityList,useEntityRecord2 as useEntityRecord,useEntityUpdate2 as useEntityUpdate,useEntityViewState2 as useEntityViewState,useMemoryEntityViewState2 as useMemoryEntityViewState};
@@ -30,12 +30,16 @@ or a collection.
30
30
  `contract`. Mount `RealtimeProvider` of `./realtime` inside
31
31
  `CollectiveIntelligenceProvider`; the provider feeds the Change Hints of its
32
32
  one connection to the collections. A collection with no server seed first
33
- loads every record of the topic, and its stream starts at that read. If
34
- that first load fails, the collection is ready with no rows, reports
35
- `RecordSyncFailed`, and loads the topic again as a reload. The collection
33
+ loads every record of the topic, and its stream starts at that read. The
34
+ collection is ready only once that first load is in place: it is never
35
+ ready with rows it did not load. A first load that CI may still answer
36
+ (`retrying`) is tried again with backoff while the collection stays loading; the retries stop once 60 seconds have passed, so the last try starts within about 2.5 minutes and ends within about 3. A first load that CI refuses, or whose retries
37
+ run out, gives the collection the error status with `RecordSyncFailed`. An
38
+ open of the topic again (the `retry()` of `useRecordCollection`) loads it
39
+ again, for every view of the collection. The collection
36
40
  applies Change Hints, removes a record on a `leave` or `delete` hint, and
37
41
  reloads on every Resync. A reload whose load fails, or a read by id of a
38
- `change` hint that fails, is tried again with backoff for up to 60 seconds.
42
+ `change` hint that fails, is tried again with backoff on the same schedule: the retries stop once 60 seconds have passed, and the last try ends within about 3 minutes.
39
43
  If a reload still fails, the collection keeps its rows, reports
40
44
  `RecordSyncFailed`, applies the Change Hints it holds, and reloads with its
41
45
  next batch of Change Hints. If a read still fails, the collection keeps
@@ -67,7 +71,10 @@ writes. Pass one `queryClient` from a layout above the routes.
67
71
  To show a loading state and an error state with a bound, open the collection
68
72
  with `useRecordCollection(open)`: `idle` (no user), `opening`, `ready` once
69
73
  the first rows are loaded, or `failed` after 20 s at the latest, with
70
- `retry()`. Keep `open` a module constant or memoized. Do not write your own
74
+ `retry()`. The status follows the collection's own: a failed first load gives
75
+ `failed` with its error, every view of one collection moves together, and
76
+ `retry()` in one view loads a failed collection again for all of its views.
77
+ Keep `open` a module constant or memoized. Do not write your own
71
78
  `runFork` opener that keeps no failure: a failed open then shows loading
72
79
  forever.
73
80
 
@@ -214,10 +221,24 @@ skill for the steps. The parts:
214
221
  that identity's collections do. A realtime seed's `load` returns
215
222
  `{ records, position }`; the browser stream of the topic starts at that
216
223
  `position`, so it misses no change after the read and repeats none.
217
- - `<RecordSeedBoundary seed>` hydrates the seed in the browser, inside the SDK
218
- provider, which gives the identity's DbClient to its tree. While no user is
219
- signed in, the seed waits and hydrates at the sign-in. A seed made for
220
- another identity, or with no `identity`, never hydrates.
224
+ - `<RecordSeedBoundary seed>` hydrates the seed inside the SDK provider. `seed`
225
+ is the seed or its promise: pass the promise of `seedRecords` un-awaited and
226
+ wrap the boundary in `<Suspense>`, so the rows stream into the HTML. A
227
+ promise of `null` gives no seed.
228
+ - `seedRecords` names the Seed Owner (`RecordSeed.owner`). While the provider
229
+ does not know its identity yet (`pending`, or its first `unauthenticated`),
230
+ the boundary opens the owner's Provisional Scope, hydrates it and gives it
231
+ to its subtree, on the server and in the browser. When the provider's
232
+ identity arrives with the owner's key, it adopts that scope: the same rows,
233
+ no second read. An identity of another key drops the seeded rows and
234
+ reports `RecordIdentityMismatch`. With no identity within the Identity Wait
235
+ (10 s), the seed no longer applies and `RecordIdentityMissing` is reported;
236
+ the collections load themselves. A seed with no `owner` hydrates only into
237
+ the scope of its identity, with the same bound.
238
+ - `useRecordCollection` gives a seeded collection `ready` with its rows in the
239
+ render that hydrated it.
240
+ - `seedRecords(sources, { wait })` waits at most 8 s (the Seed Wait) for its
241
+ reads; a late collection is left out of the seed and loads in the browser.
221
242
  - A seeded collection reads nothing on its first render. A seeded Query
222
243
  Record Collection takes its seed as fresh for one minute after it hydrated,
223
244
  until its first browser update; an invalidation still reads it again.
@@ -226,6 +247,28 @@ The `react-server` build of `./records` holds the server values. TypeScript
226
247
  sees `getRequestClients` and `seedRecords` in every build; a client component
227
248
  that imports them fails when it bundles.
228
249
 
250
+ ### Client seed from plain data
251
+
252
+ A collection that the browser opens later (a lazily mounted view) can start
253
+ from a read the app already made, with no dehydrated `RecordSeed`:
254
+
255
+ ```ts
256
+ collections.realtime(leadTopic, Lead, {
257
+ seed: { records, position } // records: { id, revision, value }[]
258
+ })
259
+ ```
260
+
261
+ The collection takes `records` as its rows, decoded with the schema, and is
262
+ ready at once. With `position` it makes no first load: its stream starts at
263
+ `position`, so it misses no change after the read. With no `position` the
264
+ seed cannot tell where the stream must start (a topic that joins after others
265
+ caught up starts at the cursor, past the changes since the seed's read): the
266
+ rows show at once, and one load of the topic replaces them and starts the
267
+ stream. A record that does not decode is left out and reported as
268
+ `RecordSyncFailed` in the collection's health. The seed counts only when the
269
+ open creates the collection: a collection of the topic that is already open
270
+ keeps its rows and ignores the seed.
271
+
229
272
  ## Outbox
230
273
 
231
274
  The SDK provider keeps the pending writes of the signed-in user and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-client-sdk-react",
3
- "version": "0.13.4",
3
+ "version": "0.13.6",
4
4
  "description": "React bindings for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -65,12 +65,12 @@
65
65
  "type-check": "bun check --no-script -p tsconfig.json"
66
66
  },
67
67
  "dependencies": {
68
- "@collective-intelligence/effect-xstate": "0.13.4",
69
- "@collective-intelligence/external-apps-client-sdk": "0.13.4",
68
+ "@collective-intelligence/effect-xstate": "0.13.6",
69
+ "@collective-intelligence/external-apps-client-sdk": "0.13.6",
70
70
  "nuqs": "2.10.1"
71
71
  },
72
72
  "peerDependencies": {
73
- "@collective-intelligence/ui-react": "0.13.4",
73
+ "@collective-intelligence/ui-react": "0.13.6",
74
74
  "@tanstack/db": "1.0.0-rc.1.5",
75
75
  "@tanstack/offline-transactions": "1.2.1",
76
76
  "@tanstack/query-core": "^5.101.4",
@@ -86,7 +86,7 @@
86
86
  "access": "public"
87
87
  },
88
88
  "devDependencies": {
89
- "@collective-intelligence/ui-react": "0.13.4",
89
+ "@collective-intelligence/ui-react": "0.13.6",
90
90
  "@effect/eslint-plugin": "0.3.2",
91
91
  "@oxlint/plugins": "1.94.0",
92
92
  "@punks/lints": "0.2.0",
@@ -119,5 +119,5 @@
119
119
  "vitest": "4.1.10",
120
120
  "xstate": "5.33.3"
121
121
  },
122
- "gitHead": "101d13284116c4551c026fcdff249f7651d0a0b8"
122
+ "gitHead": "c4dd066c416f3d4d8c2653886d68fd2b52916c27"
123
123
  }
@@ -37,12 +37,14 @@ server rendering off. Follow these steps in its place.
37
37
  Done when no cached function returns a seed.
38
38
  4. **Hydrate in the browser.** Render `<RecordSeedBoundary seed={seed}>`
39
39
  inside the SDK provider, around the client components that read the
40
- collections. They open the collections through `useRecordRuntime()` and
41
- `RecordCollections`, and read rows with `useLiveQuery`. While no user is
42
- signed in, the seed waits and hydrates at the sign-in; give the entity
43
- source the session at its first render to show the rows in the first
44
- HTML. Done when the client component renders rows with no loading state
45
- on first load.
40
+ collections; pass the promise of `seedRecords` un-awaited and wrap the
41
+ boundary in `<Suspense>`. The client components open the collections with
42
+ `useRecordCollection` (a seeded one is `ready` in the same render) and read
43
+ rows with `useLiveQuery`. While the entity source does not know its
44
+ identity yet (`pending`), the seed opens its Seed Owner's scope, so the
45
+ rows are in the first HTML; the provider adopts that scope when the
46
+ identity arrives. Done when the client component renders rows with no
47
+ loading state on first load.
46
48
  5. **Keep the server values on the server.** Import `getRequestClients` and
47
49
  `seedRecords` only in server components; a client component that imports
48
50
  them fails when it bundles. Done when the build passes.
@@ -1,2 +0,0 @@
1
- "use client";
2
- import{RecordWriteConflict2,RecordWriteOutcomeUnknown2,RecordSyncFailed2,RecordId2,RecordRevision,IdempotencyKey2,targetCollections,RecordWrites2,RecordCollections2}from"./index-4ffh8knd.js";import{entityWriteTarget2,awaitEntityAnswer,recordLayerOf}from"./index-zhh7j4d6.js";import{entityScopeError}from"./index-hmgpja4s.js";import"./index-xmbt130r.js";import{newRecordId}from"./index-stkdxnjr.js";import*as Cause from"effect/Cause";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Schema2 from"effect/Schema";var runEffect=async(runtime,effect,signal)=>await runtime.runPromise(effect,signal===undefined?undefined:{signal});import{CiError,CiErrorCode,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import*as Schema from"effect/Schema";var isCiErrorCode=Schema.is(CiErrorCode);var writeFailure=(error)=>error.code==="transport_error"?new CiTransportError({cause:error}):new CiError({code:isCiErrorCode(error.code)?error.code:"invalid_request",details:error.outcome===undefined?{...error.details,resourceCode:error.code}:{...error.details,outcome:error.outcome,resourceCode:error.code},message:error.message,retryable:error.retryable});var entityValue=Schema2.Record(Schema2.String,Schema2.Unknown);var holdingCollection=(dbClient,target,id)=>{const holding=targetCollections(dbClient,target).find((entry)=>entry.collection.get(id)!==undefined);return holding===undefined?undefined:{collection:holding.collection,kind:holding.kind}};var blindRevisionOf=(contract,write)=>write.operation!=="create"&&contract.capabilities.get!==true?write.input.expectedRevision:undefined;var writeHolding=(found,id,blindRevision)=>{if(blindRevision===undefined||found?.kind==="realtime"){return found}const row=found?.collection.get(id);return row!==undefined&&(row.$hasPendingWrites||row.revision===blindRevision)?found:undefined};var failed=(error)=>({correlationId:"record-layer",error,ok:false});var failureOf=(error)=>{if(Schema2.is(RecordWriteConflict2)(error)){return failed({code:"conflict",message:error.message,outcome:"rejected",retryable:false})}if(Schema2.is(RecordWriteOutcomeUnknown2)(error)){return failed({code:"transport_error",message:error.message,outcome:"uncertain",retryable:true})}return failed({code:"invalid_request",message:error.message,outcome:"rejected",retryable:false})};var unreadable=(id)=>failed({code:"not_found",message:`The record ${id} is not readable now`,outcome:"not_dispatched",retryable:true});var staleRevision=(id)=>failed({code:"conflict",message:`The record ${id} changed since its edit began`,outcome:"not_dispatched",retryable:false});var readRecord=(client,id)=>Effect.tryPromise({catch:(cause)=>new RecordSyncFailed2({cause,message:`The read of the record ${id} did not arrive`,retrying:true}),try:(signal)=>client.get({id},{signal})}).pipe(Effect.flatMap((result)=>{if(result.ok){return Effect.succeed([{id:result.value.id,revision:result.value.revision,value:result.value.value}])}return result.error.code==="not_found"||result.error.code==="forbidden"?Effect.succeed([]):Effect.fail(new RecordSyncFailed2({cause:result.error,message:result.error.message,retrying:result.error.retryable}))}));var blindRows=(options,revision)=>{const known=options.cached();return Effect.succeed([{id:options.id,revision,value:known?.revision===revision?known.value:{}}])};var unreadableLoad=(id)=>Effect.fail(new RecordSyncFailed2({cause:undefined,message:`The record ${id} cannot be read by id`,retrying:false}));var recordRows=(options)=>Effect.flatMap(Effect.service(RecordCollections2),(collections)=>{let loads=0;const blind=options.blindRevision;return collections.query({load:Effect.suspend(()=>{loads+=1;if(blind!==undefined){return loads>1?unreadableLoad(options.id):blindRows(options,blind)}if(loads>1){return readRecord(options.client,options.id)}if(options.created){return Effect.succeed([])}const known=options.cached();return known===undefined?readRecord(options.client,options.id):Effect.succeed([{id:known.id,revision:known.revision,value:known.value}])}),queryKey:blind===undefined?[...options.resourceKey,"record-rows",options.id]:[...options.resourceKey,"record-rows",options.id,blind],schema:entityValue,target:options.target})});var reload=(collection)=>Effect.ignore(Effect.tryPromise(async()=>{const utils=collection.utils;await utils.refetch()}));var recordWrite=Effect.fn("EntityHooks.write")(function*entityWrite(options){const{client,contract,resourceKey,write}=options;const target=entityWriteTarget2(contract);const id=write.operation==="create"?write.input.id??newRecordId():write.input.id;yield*Effect.annotateCurrentSpan({"entity.contract":contract.id,"record.id":id,"write.kind":write.operation});const blindRevision=blindRevisionOf(contract,write);const holding=write.operation==="create"?undefined:writeHolding(holdingCollection(options.dbClient,target,id),id,blindRevision);const collection=holding?.collection??(yield*recordRows({blindRevision,cached:()=>options.cached(id),client,created:write.operation==="create",id,resourceKey,target}));yield*write.operation==="create"?Effect.sync(()=>{collection.preload().catch(constVoid)}):Effect.ignore(Effect.tryPromise(()=>collection.preload()));const writes=yield*RecordWrites2;const base={collection,id:RecordId2.make(id),idempotencyKey:IdempotencyKey2.make(write.input.idempotencyKey),target};if(write.operation==="create"){const value=write.input.value;yield*writes.create({...base,value});return}const edited=(current)=>current!==undefined&&!current.$hasPendingWrites&&current.revision!==write.input.expectedRevision;if(!options.resend){if(blindRevision===undefined&&holding?.kind!=="realtime"&&edited(collection.get(id))){yield*reload(collection)}const row=collection.get(id);if(row===undefined){return unreadable(id)}if(edited(row)){return staleRevision(id)}}const checked={...base,expectedRevision:collection.get(id)?.revision===null?null:RecordRevision.make(write.input.expectedRevision)};if(write.operation==="update"){const change=write.input.value;yield*writes.update({...checked,change});return}yield*writes.delete(checked)});var openRecordLayer=(queryClient)=>{recordLayerOf(queryClient).connect()};var runEntityWrite=async(options)=>{const{identity,write}=options;if(identity===undefined){throw entityScopeError()}const layer=recordLayerOf(options.queryClient);layer.connect();const scope=layer.records(identity);const answer=awaitEntityAnswer(write.input.idempotencyKey);const departed=()=>{const error=entityScopeError(answer.take().dispatched?"uncertain":"not_dispatched");return{correlationId:error.correlationId,error:error.resourceError,ok:false}};let exit2;try{exit2=await runEffect(scope.runtime,Effect.exit(recordWrite({cached:options.cached,client:options.client,contract:options.contract,dbClient:scope.dbClient,resend:options.resend,resourceKey:options.resourceKey,write})))}catch{return departed()}if(Exit.isFailure(exit2)&&(Cause.hasInterruptsOnly(exit2.cause)||!options.current())){return departed()}const whole=answer.take().answer;if(Exit.isSuccess(exit2)){return exit2.value??whole??failed({code:"internal",message:"CI gave no answer to the write",outcome:"uncertain",retryable:false})}const failure=Cause.findErrorOption(exit2.cause);if(failure._tag==="None"){throw Cause.squash(exit2.cause)}return whole!==undefined&&!whole.ok?whole:failureOf(failure.value)};export{openRecordLayer,runEntityWrite,writeFailure};