@swirls/looms 0.14.0 → 0.16.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.
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Looms debugger</title>
7
- <script type="module" crossorigin src="./assets/index-CtGiJU8b.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-Br9tGbPI.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CbXtAM7H.js">
9
9
  <link rel="stylesheet" crossorigin href="./assets/index-CO5gIvV8.css">
10
10
  </head>
@@ -0,0 +1,30 @@
1
+ import { type EventEnvelope } from '@swirls/looms/core';
2
+ /**
3
+ * Keeps a run's durable events on the device, so a store that has followed the run before starts
4
+ * from them and downloads only what was appended since. Ephemeral events are never kept.
5
+ *
6
+ * `key` names one view of one run on one host. A store with a thread filter has its own key.
7
+ */
8
+ export interface EventCache {
9
+ /** The events kept for `key`, in sequence order. Empty when there are none. */
10
+ load(key: string): Promise<readonly EventEnvelope[]>;
11
+ append(key: string, events: readonly EventEnvelope[]): Promise<void>;
12
+ /** Forgets `key`, as when the host's log turns out not to be the one that was kept. */
13
+ clear(key: string): Promise<void>;
14
+ }
15
+ /** An `EventCache` that lives as long as the page. Useful in tests and on hosts with no storage. */
16
+ export declare function memoryEventCache(): EventCache;
17
+ export interface IndexedDbEventCacheOptions {
18
+ /** Database name. Defaults to `looms-events`. */
19
+ name?: string;
20
+ /** How many runs to keep. The ones opened longest ago are dropped first. Defaults to 50. */
21
+ maxRuns?: number;
22
+ /** Defaults to the global `indexedDB`. */
23
+ indexedDB?: IDBFactory;
24
+ }
25
+ /**
26
+ * An `EventCache` in the browser's IndexedDB. Every failure is swallowed: a cache that cannot be
27
+ * read is an empty cache, and one that cannot be written is simply not written, so the store
28
+ * falls back to downloading the log.
29
+ */
30
+ export declare function indexedDbEventCache(options?: IndexedDbEventCacheOptions): EventCache;
@@ -0,0 +1,146 @@
1
+ import { DateTime } from 'effect';
2
+ import { decodeLoomsEvent, encodeLoomsEvent } from '@swirls/looms/core';
3
+ /** An `EventCache` that lives as long as the page. Useful in tests and on hosts with no storage. */
4
+ export function memoryEventCache() {
5
+ const kept = new Map();
6
+ return {
7
+ load: (key) => Promise.resolve(kept.get(key)?.slice() ?? []),
8
+ append: (key, events) => {
9
+ const list = kept.get(key) ?? [];
10
+ list.push(...events);
11
+ kept.set(key, list);
12
+ return Promise.resolve();
13
+ },
14
+ clear: (key) => {
15
+ kept.delete(key);
16
+ return Promise.resolve();
17
+ },
18
+ };
19
+ }
20
+ const EVENTS = 'events';
21
+ const RUNS = 'runs';
22
+ const nothing = () => [];
23
+ const ignore = () => undefined;
24
+ function done(request) {
25
+ // IndexedDB reports through callbacks; this is the one place they become a promise.
26
+ // oxlint-disable-next-line effecttsgo/new-promise
27
+ return new Promise((resolve, reject) => {
28
+ request.addEventListener('success', () => resolve(request.result));
29
+ request.addEventListener('error', () => reject(request.error ?? new Error('IndexedDB failed')));
30
+ });
31
+ }
32
+ function settled(transaction) {
33
+ // oxlint-disable-next-line effecttsgo/new-promise
34
+ return new Promise((resolve, reject) => {
35
+ transaction.addEventListener('complete', () => resolve());
36
+ const fail = () => reject(transaction.error ?? new Error('IndexedDB transaction failed'));
37
+ transaction.addEventListener('error', fail);
38
+ transaction.addEventListener('abort', fail);
39
+ });
40
+ }
41
+ function eventsOf(key) {
42
+ return IDBKeyRange.bound([key, 0], [key, Number.MAX_SAFE_INTEGER]);
43
+ }
44
+ /**
45
+ * An `EventCache` in the browser's IndexedDB. Every failure is swallowed: a cache that cannot be
46
+ * read is an empty cache, and one that cannot be written is simply not written, so the store
47
+ * falls back to downloading the log.
48
+ */
49
+ export function indexedDbEventCache(options = {}) {
50
+ const factory = options.indexedDB ?? globalThis.indexedDB;
51
+ const maxRuns = Math.max(1, options.maxRuns ?? 50);
52
+ let opening;
53
+ const open = () => {
54
+ if (opening) {
55
+ return opening;
56
+ }
57
+ const request = factory.open(options.name ?? 'looms-events', 1);
58
+ request.addEventListener('upgradeneeded', () => {
59
+ const db = request.result;
60
+ if (!db.objectStoreNames.contains(EVENTS)) {
61
+ db.createObjectStore(EVENTS, { keyPath: ['key', 'seq'] });
62
+ }
63
+ if (!db.objectStoreNames.contains(RUNS)) {
64
+ db.createObjectStore(RUNS, { keyPath: 'key' });
65
+ }
66
+ });
67
+ opening = done(request);
68
+ opening.catch(() => {
69
+ opening = undefined;
70
+ });
71
+ return opening;
72
+ };
73
+ /** Drops the runs opened longest ago once more than `maxRuns` are kept. */
74
+ const evict = (db) => {
75
+ const transaction = db.transaction([EVENTS, RUNS], 'readwrite');
76
+ const listed = done(transaction.objectStore(RUNS).getAll());
77
+ return listed.then((runs) => {
78
+ const stale = runs
79
+ .toSorted((a, b) => b.touchedAt - a.touchedAt)
80
+ .slice(maxRuns)
81
+ .map((run) => run.key);
82
+ for (const key of stale) {
83
+ transaction.objectStore(EVENTS).delete(eventsOf(key));
84
+ transaction.objectStore(RUNS).delete(key);
85
+ }
86
+ return settled(transaction);
87
+ });
88
+ };
89
+ const touch = (transaction, key) => {
90
+ transaction
91
+ .objectStore(RUNS)
92
+ .put({ key, touchedAt: DateTime.toEpochMillis(DateTime.nowUnsafe()) });
93
+ };
94
+ return {
95
+ load: (key) => {
96
+ if (!factory) {
97
+ return Promise.resolve([]);
98
+ }
99
+ return open()
100
+ .then((db) => {
101
+ const transaction = db.transaction([EVENTS, RUNS], 'readwrite');
102
+ // Rows are what `append` wrote, which is the wire encoding of an event.
103
+ const read = done(transaction.objectStore(EVENTS).getAll(eventsOf(key)));
104
+ return read.then((rows) => {
105
+ if (rows.length > 0) {
106
+ touch(transaction, key);
107
+ }
108
+ return settled(transaction).then(() => {
109
+ void evict(db).catch(ignore);
110
+ return rows.map((row) => decodeLoomsEvent(row.event, ''));
111
+ });
112
+ });
113
+ })
114
+ .catch(nothing);
115
+ },
116
+ append: (key, events) => {
117
+ if (!factory || events.length === 0) {
118
+ return Promise.resolve();
119
+ }
120
+ return open()
121
+ .then((db) => {
122
+ const transaction = db.transaction([EVENTS, RUNS], 'readwrite');
123
+ const store = transaction.objectStore(EVENTS);
124
+ for (const event of events) {
125
+ store.put({ key, seq: event.seq, event: encodeLoomsEvent(event) });
126
+ }
127
+ touch(transaction, key);
128
+ return settled(transaction);
129
+ })
130
+ .catch(ignore); // Not kept. The store downloads these again next time.
131
+ },
132
+ clear: (key) => {
133
+ if (!factory) {
134
+ return Promise.resolve();
135
+ }
136
+ return open()
137
+ .then((db) => {
138
+ const transaction = db.transaction([EVENTS, RUNS], 'readwrite');
139
+ transaction.objectStore(EVENTS).delete(eventsOf(key));
140
+ transaction.objectStore(RUNS).delete(key);
141
+ return settled(transaction);
142
+ })
143
+ .catch(ignore);
144
+ },
145
+ };
146
+ }
@@ -30,8 +30,11 @@ export declare function foldLive<S, TEvent extends AnyEventEnvelope = Registered
30
30
  export declare class ProjectionCache {
31
31
  private projectionCache;
32
32
  private foldCache;
33
- project<S>(definition: ProjectionDefinition<S>, events: readonly EventEnvelope[]): S;
33
+ private projectionOverlay;
34
+ private foldOverlay;
35
+ /** `pending` are events shown before the host confirms them; they fold after `events`. */
36
+ project<S>(definition: ProjectionDefinition<S>, events: readonly EventEnvelope[], pending?: readonly EventEnvelope[], pendingVersion?: number): S;
34
37
  /** A retry can supersede events already folded, so a batch containing one refolds from scratch. */
35
- fold<S, TEvent extends AnyEventEnvelope = RegisteredEvent>(definition: LiveFoldDefinition<S, TEvent>, events: readonly TEvent[]): S;
38
+ fold<S, TEvent extends AnyEventEnvelope = RegisteredEvent>(definition: LiveFoldDefinition<S, TEvent>, events: readonly TEvent[], pending?: readonly TEvent[], pendingVersion?: number): S;
36
39
  clear(): void;
37
40
  }
@@ -30,18 +30,41 @@ function advanceCache(cache, definition, events, compute, canAppend = () => true
30
30
  cache.set(definition, { state, upTo: events.length });
31
31
  return state;
32
32
  }
33
+ /**
34
+ * Folds events not yet confirmed on top of the confirmed state. The confirmed fold stays
35
+ * incremental; the overlay is refolded only when the confirmed state or the pending set changes.
36
+ */
37
+ function overlay(cache, definition, base, pending, pendingVersion, compute) {
38
+ if (pending.length === 0) {
39
+ return base;
40
+ }
41
+ const cached = cache.get(definition);
42
+ if (cached && cached.base === base && cached.pending === pendingVersion) {
43
+ return cached.state;
44
+ }
45
+ const state = compute(definition, pending, base);
46
+ cache.set(definition, { base, pending: pendingVersion, state });
47
+ return state;
48
+ }
33
49
  export class ProjectionCache {
34
50
  projectionCache = new WeakMap();
35
51
  foldCache = new WeakMap();
36
- project(definition, events) {
37
- return advanceCache(this.projectionCache, definition, events, project);
52
+ projectionOverlay = new WeakMap();
53
+ foldOverlay = new WeakMap();
54
+ /** `pending` are events shown before the host confirms them; they fold after `events`. */
55
+ project(definition, events, pending = [], pendingVersion = 0) {
56
+ const base = advanceCache(this.projectionCache, definition, events, project);
57
+ return overlay(this.projectionOverlay, definition, base, pending, pendingVersion, project);
38
58
  }
39
59
  /** A retry can supersede events already folded, so a batch containing one refolds from scratch. */
40
- fold(definition, events) {
41
- return advanceCache(this.foldCache, definition, events, foldFrom, hasNoRetries);
60
+ fold(definition, events, pending = [], pendingVersion = 0) {
61
+ const base = advanceCache(this.foldCache, definition, events, foldFrom, hasNoRetries);
62
+ return overlay(this.foldOverlay, definition, base, pending, pendingVersion, foldFrom);
42
63
  }
43
64
  clear() {
44
65
  this.projectionCache = new WeakMap();
45
66
  this.foldCache = new WeakMap();
67
+ this.projectionOverlay = new WeakMap();
68
+ this.foldOverlay = new WeakMap();
46
69
  }
47
70
  }
@@ -1,5 +1,7 @@
1
- export { createLoomsStore, type LoomsClientStore, type LoomsClientStoreOptions, type LoomsConnectionStatus, type LoomsStoreQuery, type CoalesceOption, type StoreListener, } from './store';
1
+ export { createLoomsStore, isPendingEvent, type CommitOptions, type LoomsClientStore, type LoomsClientStoreOptions, type LoomsConnectionStatus, type LoomsStoreQuery, type CoalesceOption, type StoreListener, } from './store';
2
2
  export { defineLiveFold, foldLive, EventIndex, eventThreadKey, type LiveFoldDefinition, } from './derived';
3
+ export { indexedDbEventCache, memoryEventCache, type EventCache, type IndexedDbEventCacheOptions, } from './cache';
4
+ export type { StoreObservation, StoreObserver } from './observer';
3
5
  export { materializeEvents } from './materialize';
4
6
  export { emptyTables, type MaterializedTables, type RunRow, type ThreadRow } from './tables';
5
7
  export type { LoomsRegister, RegisteredEvent, AnyEventEnvelope } from '@swirls/looms/core';
@@ -1,5 +1,6 @@
1
- export { createLoomsStore, } from './store.js';
1
+ export { createLoomsStore, isPendingEvent, } from './store.js';
2
2
  export { defineLiveFold, foldLive, EventIndex, eventThreadKey, } from './derived.js';
3
+ export { indexedDbEventCache, memoryEventCache, } from './cache.js';
3
4
  export { materializeEvents } from './materialize.js';
4
5
  export { emptyTables } from './tables.js';
5
6
  export { LoomsProvider, useRunStore, useProjection, useRunSelector, useRunSummary, useRunEvents, useThreadTree, useEventCounts, useEventBySeq, useLatestEvent, useLiveFold, } from './react.js';
@@ -0,0 +1,44 @@
1
+ /**
2
+ * What a client store reports about how the run felt to use: how long it took to show, and how
3
+ * long each write took to be acknowledged and then confirmed. Durations are in milliseconds.
4
+ */
5
+ export type StoreObservation = {
6
+ /** The store holds everything the log had when it connected. Reported once per store. */
7
+ readonly type: 'store.synced';
8
+ readonly runId: string;
9
+ readonly at: number;
10
+ /** From the store's creation. */
11
+ readonly durationMs: number;
12
+ readonly eventCount: number;
13
+ /** How many of those events came from the device's cache and were not downloaded. */
14
+ readonly cachedEvents: number;
15
+ } | {
16
+ readonly type: 'store.connection';
17
+ readonly runId: string;
18
+ readonly at: number;
19
+ readonly status: 'connecting' | 'live' | 'reconnecting';
20
+ } | {
21
+ /** The host answered a commit. */
22
+ readonly type: 'commit.acked';
23
+ readonly runId: string;
24
+ readonly at: number;
25
+ readonly durationMs: number;
26
+ readonly eventCount: number;
27
+ readonly optimistic: boolean;
28
+ } | {
29
+ /** The host's copy of an optimistic commit arrived on the event stream. */
30
+ readonly type: 'commit.confirmed';
31
+ readonly runId: string;
32
+ readonly at: number;
33
+ /** From the call to `commit`. */
34
+ readonly durationMs: number;
35
+ } | {
36
+ readonly type: 'commit.failed';
37
+ readonly runId: string;
38
+ readonly at: number;
39
+ readonly durationMs: number;
40
+ readonly message: string;
41
+ };
42
+ export interface StoreObserver {
43
+ observe(observation: StoreObservation): void;
44
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,20 +1,35 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import { type AnyEventEnvelope, type ProjectionDefinition, type RegisteredEvent, type RunAttributes, type RunLaunchSource, type RunStatus, type SubscriptionTransport, type ThreadTree } from '@swirls/looms/core';
3
+ import type { EventCache } from './cache';
3
4
  import { defineLiveFold, foldLive, type LiveFoldDefinition } from './derived';
4
- import { createLoomsStore, type CoalesceOption, type LoomsClientStore, type LoomsConnectionStatus } from './store';
5
+ import type { StoreObserver } from './observer';
6
+ import { createLoomsStore, isPendingEvent, type CoalesceOption, type LoomsClientStore, type LoomsConnectionStatus } from './store';
5
7
  export interface LoomsProviderProps {
6
8
  children: ReactNode;
7
9
  endpoint?: string;
8
10
  coalesce?: CoalesceOption;
9
11
  transport?: SubscriptionTransport;
12
+ /**
13
+ * How long a run's store stays connected and in memory after the last component using it
14
+ * unmounts. Returning to the run within that time shows it at once, with no download. Defaults
15
+ * to five seconds.
16
+ */
17
+ retainMs?: number;
18
+ /** Keeps each run's durable events on the device. See `indexedDbEventCache`. */
19
+ cache?: EventCache;
20
+ /** Told how long each run took to show and how long each commit took. */
21
+ observer?: StoreObserver;
10
22
  }
11
23
  interface ProviderContextValue {
12
24
  endpoint: string;
13
25
  coalesce?: CoalesceOption;
14
26
  transport?: SubscriptionTransport;
27
+ retainMs?: number;
28
+ cache?: EventCache;
29
+ observer?: StoreObserver;
15
30
  }
16
31
  /** Root provider that supplies the Looms host endpoint to run stores. */
17
- export declare function LoomsProvider({ children, endpoint, coalesce, transport, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
32
+ export declare function LoomsProvider({ children, endpoint, coalesce, transport, retainMs, cache, observer, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
18
33
  export interface UseRunStoreOptions {
19
34
  endpoint?: string;
20
35
  reconnectDelayMs?: number;
@@ -22,6 +37,9 @@ export interface UseRunStoreOptions {
22
37
  transport?: SubscriptionTransport;
23
38
  threadId?: string;
24
39
  includeEphemeral?: boolean;
40
+ /** See `LoomsClientStoreOptions.fromSeq`. Read once, when the store is first created. */
41
+ fromSeq?: number;
42
+ retainMs?: number;
25
43
  }
26
44
  /**
27
45
  * Acquires a non-subscribing handle to the run store.
@@ -47,6 +65,8 @@ export interface RunSummary {
47
65
  readonly launchedBy: RunLaunchSource | undefined;
48
66
  readonly attributes: RunAttributes;
49
67
  readonly connection: LoomsConnectionStatus;
68
+ /** False while the store is still catching up to the log, when empty state means "loading". */
69
+ readonly synced: boolean;
50
70
  }
51
71
  /** Lightweight subscription to top-level run metadata and connection status. */
52
72
  export declare function useRunSummary<TEvent extends AnyEventEnvelope = RegisteredEvent>(store: LoomsClientStore<TEvent>): RunSummary;
@@ -64,8 +84,8 @@ export declare function useEventBySeq<TEvent extends AnyEventEnvelope = Register
64
84
  export declare function useLatestEvent<TEvent extends AnyEventEnvelope = RegisteredEvent>(store: LoomsClientStore<TEvent>, type: string): TEvent | undefined;
65
85
  /** Subscribe to a live fold, which includes ephemeral events. */
66
86
  export declare function useLiveFold<S, TEvent extends AnyEventEnvelope = RegisteredEvent>(store: LoomsClientStore<TEvent>, fold: LiveFoldDefinition<S, TEvent>): S;
67
- export { createLoomsStore };
87
+ export { createLoomsStore, isPendingEvent };
68
88
  export { defineLiveFold, foldLive };
69
- export type { LoomsClientStore, LoomsClientStoreOptions, LoomsConnectionStatus, LoomsStoreQuery, CoalesceOption, StoreListener, } from './store';
89
+ export type { LoomsClientStore, CommitOptions, LoomsClientStoreOptions, LoomsConnectionStatus, LoomsStoreQuery, CoalesceOption, StoreListener, } from './store';
70
90
  export type { LiveFoldDefinition } from './derived';
71
91
  export type { LoomsRegister, RegisteredEvent, AnyEventEnvelope } from '@swirls/looms/core';
@@ -2,9 +2,9 @@ import { Effect, Fiber } from 'effect';
2
2
  import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useRef, useSyncExternalStore, } from 'react';
3
3
  import { isTerminalStatus, sameStringRecord, threadTree, toThreadTree, } from '@swirls/looms/core';
4
4
  import { defineLiveFold, foldLive } from './derived.js';
5
- import { createLoomsStore, } from './store.js';
5
+ import { createLoomsStore, isPendingEvent, } from './store.js';
6
6
  const LoomsContext = createContext({ endpoint: '' });
7
- const GRACE_MS = 5_000;
7
+ const DEFAULT_RETAIN_MS = 5_000;
8
8
  const registry = new Map();
9
9
  function registryKey(runId, identity) {
10
10
  return [
@@ -23,8 +23,8 @@ function disposeEntry(key) {
23
23
  entry.store.dispose();
24
24
  registry.delete(key);
25
25
  }
26
- function scheduleDisposal(key) {
27
- return Effect.runFork(Effect.sleep(GRACE_MS).pipe(Effect.andThen(Effect.sync(() => disposeEntry(key)))));
26
+ function scheduleDisposal(key, retainMs) {
27
+ return Effect.runFork(Effect.sleep(retainMs).pipe(Effect.andThen(Effect.sync(() => disposeEntry(key)))));
28
28
  }
29
29
  function peekStore(runId, identity) {
30
30
  const key = registryKey(runId, identity);
@@ -40,11 +40,17 @@ function peekStore(runId, identity) {
40
40
  transport: identity.transport,
41
41
  threadId: identity.threadId,
42
42
  includeEphemeral: identity.includeEphemeral,
43
+ fromSeq: identity.fromSeq,
44
+ cache: identity.cache,
45
+ observer: identity.observer,
43
46
  });
47
+ const retainMs = Math.max(0, identity.retainMs ?? DEFAULT_RETAIN_MS);
44
48
  registry.set(key, {
45
49
  store,
46
50
  refs: 0,
47
- disposal: scheduleDisposal(key),
51
+ retainMs,
52
+ // A store that is peeked at and never mounted is not kept for the full retention.
53
+ disposal: scheduleDisposal(key, Math.min(retainMs, DEFAULT_RETAIN_MS)),
48
54
  });
49
55
  return store;
50
56
  }
@@ -69,12 +75,12 @@ function releaseStore(runId, identity) {
69
75
  }
70
76
  entry.refs = Math.max(0, entry.refs - 1);
71
77
  if (entry.refs === 0 && entry.disposal === undefined) {
72
- entry.disposal = scheduleDisposal(key);
78
+ entry.disposal = scheduleDisposal(key, entry.retainMs);
73
79
  }
74
80
  }
75
81
  /** Root provider that supplies the Looms host endpoint to run stores. */
76
- export function LoomsProvider({ children, endpoint = '', coalesce, transport, }) {
77
- const value = useMemo(() => ({ endpoint, coalesce, transport }), [endpoint, coalesce, transport]);
82
+ export function LoomsProvider({ children, endpoint = '', coalesce, transport, retainMs, cache, observer, }) {
83
+ const value = useMemo(() => ({ endpoint, coalesce, transport, retainMs, cache, observer }), [endpoint, coalesce, transport, retainMs, cache, observer]);
78
84
  return createElement(LoomsContext.Provider, { value, children });
79
85
  }
80
86
  /**
@@ -90,6 +96,8 @@ export function useRunStore(runId, options) {
90
96
  const transport = options?.transport ?? context.transport;
91
97
  const threadId = options?.threadId;
92
98
  const includeEphemeral = options?.includeEphemeral;
99
+ const fromSeq = options?.fromSeq;
100
+ const retainMs = options?.retainMs ?? context.retainMs;
93
101
  const identity = {
94
102
  endpoint,
95
103
  reconnectDelayMs,
@@ -97,6 +105,10 @@ export function useRunStore(runId, options) {
97
105
  transport,
98
106
  threadId,
99
107
  includeEphemeral,
108
+ fromSeq,
109
+ retainMs,
110
+ cache: context.cache,
111
+ observer: context.observer,
100
112
  };
101
113
  const store = peekStore(runId, identity);
102
114
  useEffect(() => {
@@ -141,7 +153,8 @@ function shallowEqualSummary(a, b) {
141
153
  a.startedAt === b.startedAt &&
142
154
  a.launchedBy === b.launchedBy &&
143
155
  sameStringRecord(a.attributes, b.attributes) &&
144
- a.connection === b.connection);
156
+ a.connection === b.connection &&
157
+ a.synced === b.synced);
145
158
  }
146
159
  /** Lightweight subscription to top-level run metadata and connection status. */
147
160
  export function useRunSummary(store) {
@@ -159,6 +172,7 @@ export function useRunSummary(store) {
159
172
  launchedBy: run?.launchedBy ?? undefined,
160
173
  attributes: run?.attributes ?? {},
161
174
  connection: s.status(),
175
+ synced: s.synced(),
162
176
  };
163
177
  }, []);
164
178
  return useRunSelector(store, selector, shallowEqualSummary);
@@ -194,5 +208,5 @@ export function useLiveFold(store, fold) {
194
208
  const getSnapshot = useCallback(() => store.fold(fold), [store, fold]);
195
209
  return useStoreSnapshot(store, getSnapshot);
196
210
  }
197
- export { createLoomsStore };
211
+ export { createLoomsStore, isPendingEvent };
198
212
  export { defineLiveFold, foldLive };
@@ -1,12 +1,41 @@
1
1
  import { type SubscriptionSocketConstructor } from '@swirls/looms/client';
2
2
  import { type AnyEventEnvelope, type EventInput, type ProjectionDefinition, type RegisteredEvent, type SubscriptionTransport } from '@swirls/looms/core';
3
+ import type { EventCache } from './cache';
3
4
  import { type LiveFoldDefinition } from './derived';
4
5
  import { type CoalesceOption } from './notify';
6
+ import type { StoreObserver } from './observer';
5
7
  import { type MaterializedTables } from './tables';
6
8
  export type { CoalesceOption } from './notify';
7
9
  /** Fired after the store version bumps. Re-read via `events()` / `getState()` / `query`. */
8
10
  export type StoreListener = () => void;
9
11
  export type LoomsConnectionStatus = 'connecting' | 'live' | 'reconnecting';
12
+ /** True for an event shown optimistically that the host has not confirmed yet. */
13
+ export declare function isPendingEvent(event: {
14
+ readonly seq: number;
15
+ }): boolean;
16
+ export interface CommitOptions {
17
+ /**
18
+ * Show the events at once, before the host confirms them. They are folded after every confirmed
19
+ * event, replaced by the host's own copies when those arrive, and removed if the commit fails,
20
+ * in which case `commit` rejects. Defaults to the store's `optimistic` option.
21
+ */
22
+ optimistic?: boolean;
23
+ /**
24
+ * Identifies this commit to the host, which ignores a repeat of it. An optimistic commit is
25
+ * matched to its confirmed events by this key; one is generated when it is left out.
26
+ */
27
+ idempotencyKey?: string;
28
+ /**
29
+ * Sends the commit somewhere other than the run's signal route, such as a route of your own that
30
+ * signs the events. It must signal the run with the `idempotencyKey` it is given, or an
31
+ * optimistic commit cannot be matched to what the host records.
32
+ */
33
+ send?: (commit: {
34
+ readonly events: readonly EventInput[];
35
+ readonly idempotencyKey: string | undefined;
36
+ readonly signal: AbortSignal;
37
+ }) => Promise<void>;
38
+ }
10
39
  export interface LoomsClientStoreOptions {
11
40
  /** Run id for this client store. */
12
41
  storeId: string;
@@ -27,6 +56,21 @@ export interface LoomsClientStoreOptions {
27
56
  threadId?: string;
28
57
  includeEphemeral?: boolean;
29
58
  webSocket?: SubscriptionSocketConstructor;
59
+ /**
60
+ * First sequence number to follow. Use it with state you already hold up to `fromSeq - 1`, such
61
+ * as a projection the host served, so the store does not download the log behind it. Events
62
+ * before it are never seen: `events()`, projections and the run summary cover only what follows.
63
+ */
64
+ fromSeq?: number;
65
+ /** Whether `commit` shows its events before the host confirms them. Defaults to false. */
66
+ optimistic?: boolean;
67
+ /**
68
+ * Keeps the run's durable events on the device. A store that has followed the run before starts
69
+ * from them and downloads only what was appended since. Not used together with `fromSeq`.
70
+ */
71
+ cache?: EventCache;
72
+ /** Told how long the run took to show and how long each commit took. */
73
+ observer?: StoreObserver;
30
74
  }
31
75
  export interface LoomsStoreQuery<TEvent extends AnyEventEnvelope = RegisteredEvent> {
32
76
  events: (options?: {
@@ -44,6 +88,11 @@ export interface LoomsClientStore<TEvent extends AnyEventEnvelope = RegisteredEv
44
88
  storeId: string;
45
89
  version: () => number;
46
90
  status: () => LoomsConnectionStatus;
91
+ /**
92
+ * True once the store holds everything the log had when the subscription opened. Until then an
93
+ * empty projection means "still loading", not "nothing there".
94
+ */
95
+ synced: () => boolean;
47
96
  getState: () => MaterializedTables;
48
97
  events: (options?: {
49
98
  threadId?: string;
@@ -53,7 +102,9 @@ export interface LoomsClientStore<TEvent extends AnyEventEnvelope = RegisteredEv
53
102
  project<S>(definition: ProjectionDefinition<S>): S;
54
103
  fold<S>(definition: LiveFoldDefinition<S, TEvent>): S;
55
104
  flush: () => void;
56
- commit: (event: EventInput | readonly EventInput[]) => Promise<void>;
105
+ /** Events shown optimistically that the host has not confirmed yet. */
106
+ pending: () => readonly TEvent[];
107
+ commit: (event: EventInput | readonly EventInput[], options?: CommitOptions) => Promise<void>;
57
108
  sync: () => Promise<void>;
58
109
  dispose: () => void;
59
110
  }