@powersync/react 0.0.0-dev-20260630144038 → 0.0.0-dev-20261015114518

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +15 -0
  2. package/lib/hooks/PowerSyncContext.d.ts +4 -2
  3. package/lib/hooks/PowerSyncContext.js +7 -1
  4. package/lib/hooks/PowerSyncContext.js.map +1 -1
  5. package/lib/hooks/streams.d.ts +4 -3
  6. package/lib/hooks/streams.js +11 -10
  7. package/lib/hooks/streams.js.map +1 -1
  8. package/lib/hooks/suspense/SuspenseQueryCache.d.ts +46 -0
  9. package/lib/hooks/suspense/SuspenseQueryCache.js +231 -0
  10. package/lib/hooks/suspense/SuspenseQueryCache.js.map +1 -0
  11. package/lib/hooks/suspense/useSuspenseQuery.d.ts +3 -3
  12. package/lib/hooks/suspense/useSuspenseQuery.js +28 -7
  13. package/lib/hooks/suspense/useSuspenseQuery.js.map +1 -1
  14. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js +60 -24
  15. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js.map +1 -1
  16. package/lib/hooks/useStatus.d.ts +7 -1
  17. package/lib/hooks/useStatus.js +11 -6
  18. package/lib/hooks/useStatus.js.map +1 -1
  19. package/lib/hooks/watched/QueryRunner.d.ts +90 -0
  20. package/lib/hooks/watched/QueryRunner.js +366 -0
  21. package/lib/hooks/watched/QueryRunner.js.map +1 -0
  22. package/lib/hooks/watched/useQuery.js +14 -39
  23. package/lib/hooks/watched/useQuery.js.map +1 -1
  24. package/lib/hooks/watched/useWatchedQuerySubscription.d.ts +1 -1
  25. package/lib/hooks/watched/useWatchedQuerySubscription.js.map +1 -1
  26. package/lib/hooks/watched/watch-types.d.ts +39 -3
  27. package/lib/hooks/watched/watch-utils.d.ts +3 -15
  28. package/lib/hooks/watched/watch-utils.js +5 -31
  29. package/lib/hooks/watched/watch-utils.js.map +1 -1
  30. package/lib/index.d.ts +2 -2
  31. package/lib/index.js +1 -1
  32. package/lib/index.js.map +1 -1
  33. package/package.json +12 -10
  34. package/src/hooks/PowerSyncContext.ts +9 -3
  35. package/src/hooks/streams.ts +14 -20
  36. package/src/hooks/suspense/SuspenseQueryCache.ts +253 -0
  37. package/src/hooks/suspense/useSuspenseQuery.ts +40 -13
  38. package/src/hooks/suspense/useWatchedQuerySuspenseSubscription.ts +65 -25
  39. package/src/hooks/useStatus.ts +21 -7
  40. package/src/hooks/watched/QueryRunner.ts +484 -0
  41. package/src/hooks/watched/useQuery.ts +15 -40
  42. package/src/hooks/watched/useWatchedQuerySubscription.ts +2 -2
  43. package/src/hooks/watched/watch-types.ts +42 -3
  44. package/src/hooks/watched/watch-utils.ts +8 -54
  45. package/src/index.ts +8 -2
  46. package/lib/QueryStore.d.ts +0 -10
  47. package/lib/QueryStore.js +0 -63
  48. package/lib/QueryStore.js.map +0 -1
  49. package/lib/hooks/suspense/suspense-utils.d.ts +0 -16
  50. package/lib/hooks/suspense/suspense-utils.js +0 -76
  51. package/lib/hooks/suspense/suspense-utils.js.map +0 -1
  52. package/lib/hooks/suspense/useSingleSuspenseQuery.d.ts +0 -10
  53. package/lib/hooks/suspense/useSingleSuspenseQuery.js +0 -73
  54. package/lib/hooks/suspense/useSingleSuspenseQuery.js.map +0 -1
  55. package/lib/hooks/suspense/useWatchedSuspenseQuery.d.ts +0 -6
  56. package/lib/hooks/suspense/useWatchedSuspenseQuery.js +0 -26
  57. package/lib/hooks/suspense/useWatchedSuspenseQuery.js.map +0 -1
  58. package/lib/hooks/watched/useSingleQuery.d.ts +0 -6
  59. package/lib/hooks/watched/useSingleQuery.js +0 -59
  60. package/lib/hooks/watched/useSingleQuery.js.map +0 -1
  61. package/lib/hooks/watched/useWatchedQuery.d.ts +0 -13
  62. package/lib/hooks/watched/useWatchedQuery.js +0 -81
  63. package/lib/hooks/watched/useWatchedQuery.js.map +0 -1
  64. package/src/QueryStore.ts +0 -81
  65. package/src/hooks/suspense/suspense-utils.ts +0 -86
  66. package/src/hooks/suspense/useSingleSuspenseQuery.ts +0 -81
  67. package/src/hooks/suspense/useWatchedSuspenseQuery.ts +0 -36
  68. package/src/hooks/watched/useSingleQuery.ts +0 -67
  69. package/src/hooks/watched/useWatchedQuery.ts +0 -93
@@ -1,6 +1,5 @@
1
- import { WatchedQuery } from '@powersync/common';
2
- import React from 'react';
3
- import { createSuspendingPromise, useTemporaryHold } from './suspense-utils.js';
1
+ import { WatchedQuery, WatchedQueryState } from '@powersync/common';
2
+ import { useCallback, useSyncExternalStore } from 'react';
4
3
 
5
4
  /**
6
5
  * A hook to access and subscribe to the results of an existing {@link WatchedQuery}.
@@ -29,32 +28,73 @@ export const useWatchedQuerySuspenseSubscription = <
29
28
  >(
30
29
  query: Query
31
30
  ): Query['state'] => {
32
- useTemporaryHold(query);
31
+ const subscribe = useCallback((onChange: () => void) => query.registerListener({ onStateChange: onChange }), [query]);
32
+ const getSnapshot = useCallback(() => snapshotState(query), [query]);
33
+ const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
33
34
 
34
- // Force update state function
35
- const [, setUpdateCounter] = React.useState(0);
35
+ if (state.error != null) {
36
+ throw state.error;
37
+ } else if (!state.isLoading) {
38
+ return state;
39
+ } else {
40
+ // Suspend until the query has results or an error.
41
+ throw suspendUntilDataOrError(query);
42
+ }
43
+ };
44
+
45
+ let suspendingPromises: WeakMap<WatchedQuery<unknown>, Promise<void>> | undefined;
46
+ let stateSnapshots: WeakMap<WatchedQuery<unknown>, WatchedQueryState<unknown>> | undefined;
47
+
48
+ /**
49
+ * A promise that resolves once the query has loaded, cached to be suitable for hooks.
50
+ */
51
+ function suspendUntilDataOrError(query: WatchedQuery<unknown>): Promise<void> {
52
+ const promises = (suspendingPromises ??= new WeakMap());
53
+ const existing = promises.get(query);
54
+ if (existing) {
55
+ return existing;
56
+ }
36
57
 
37
- React.useEffect(() => {
38
- // This runs when the component came out of suspense
39
- // This add a permanent hold since a listener has been added to the query
58
+ const promise = new Promise<void>((resolve) => {
59
+ // The listener here will dispose itself once the loading is done.
60
+ // This decreases the number of listeners on the query even if the component is unmounted.
40
61
  const dispose = query.registerListener({
41
- onStateChange() {
42
- // Trigger rerender
43
- setUpdateCounter((prev) => prev + 1);
62
+ onStateChange: (state) => {
63
+ // Returns to the hook if loading is completed or if loading resulted in an error
64
+ if (!state.isLoading || state.error) {
65
+ promises.delete(query);
66
+ resolve();
67
+ dispose();
68
+ }
44
69
  }
45
70
  });
71
+ });
72
+ promises.set(query, promise);
73
+ return promise;
74
+ }
46
75
 
47
- return dispose;
48
- }, []);
49
-
50
- if (query.state.error != null) {
51
- // Report errors - this is caught by an error boundary
52
- throw query.state.error;
53
- } else if (!query.state.isLoading) {
54
- // Happy path data return
55
- return query.state;
56
- } else {
57
- // Notify suspense is required
58
- throw createSuspendingPromise(query);
76
+ /**
77
+ * Returns a stable copy of the query's state.
78
+ *
79
+ * Watched queries update their `state` object in place, so it can't be used as a snapshot for `useSyncExternalStore`
80
+ * directly.
81
+ */
82
+ function snapshotState<Data>(query: WatchedQuery<Data>): WatchedQueryState<Data> {
83
+ const state = query.state;
84
+ const snapshots = (stateSnapshots ??= new WeakMap());
85
+ const cached = snapshots.get(query) as WatchedQueryState<Data> | undefined;
86
+ if (
87
+ cached != null &&
88
+ cached.data === state.data &&
89
+ cached.isLoading === state.isLoading &&
90
+ cached.isFetching === state.isFetching &&
91
+ cached.error === state.error &&
92
+ cached.lastUpdated === state.lastUpdated
93
+ ) {
94
+ return cached;
59
95
  }
60
- };
96
+
97
+ const snapshot = { ...state };
98
+ snapshots.set(query, snapshot);
99
+ return snapshot;
100
+ }
@@ -1,5 +1,6 @@
1
- import { useContext, useEffect, useState } from 'react';
2
- import { PowerSyncContext } from './PowerSyncContext.js';
1
+ import { useEffect, useState } from 'react';
2
+ import { usePowerSync, usePowerSyncOrNull } from './PowerSyncContext.js';
3
+ import { SyncStatus } from '@powersync/common';
3
4
 
4
5
  /**
5
6
  * Custom hook that provides access to the current status of PowerSync.
@@ -15,12 +16,25 @@ import { PowerSyncContext } from './PowerSyncContext.js';
15
16
  * </div>
16
17
  * };
17
18
  */
18
- export function useStatus() {
19
- const powerSync = useContext(PowerSyncContext);
20
- const [syncStatus, setSyncStatus] = useState(powerSync.currentStatus);
19
+ export function useStatus(): SyncStatus {
20
+ return useStatusOrNull(false);
21
+ }
22
+
23
+ /**
24
+ * @internal
25
+ */
26
+ export function useStatusOrNull(allowNull?: boolean): SyncStatus | null;
27
+ export function useStatusOrNull(allowNull: false): SyncStatus;
28
+
29
+ export function useStatusOrNull(allowNull: boolean = true): SyncStatus | null {
30
+ // Conditional hook is okay, this is an internal hook and allowNull is a constant on each call site.
31
+ const powerSync = allowNull ? usePowerSyncOrNull() : usePowerSync();
32
+ const [syncStatus, setSyncStatus] = useState(powerSync?.currentStatus);
21
33
 
22
34
  useEffect(() => {
23
- const listener = powerSync.registerListener({
35
+ setSyncStatus(powerSync?.currentStatus);
36
+
37
+ const listener = powerSync?.registerListener({
24
38
  statusChanged: (status) => {
25
39
  setSyncStatus(status);
26
40
  }
@@ -29,5 +43,5 @@ export function useStatus() {
29
43
  return () => listener?.();
30
44
  }, [powerSync]);
31
45
 
32
- return syncStatus;
46
+ return syncStatus ?? null;
33
47
  }
@@ -0,0 +1,484 @@
1
+ import {
2
+ BaseListener,
3
+ BaseObserver,
4
+ CommonPowerSyncDatabase,
5
+ DifferentialWatchedQuery,
6
+ DifferentialWatchedQueryComparator,
7
+ WatchedQueryState
8
+ } from '@powersync/common';
9
+ import {
10
+ AdditionalOptions,
11
+ DifferentialHookOptions,
12
+ FetchReason,
13
+ QueryResult,
14
+ ReadonlyQueryResult
15
+ } from './watch-types.js';
16
+ import { WatchCompatibleQueryWithParams } from './watch-utils.js';
17
+
18
+ // We want to generate readonly results, but declare mutable results when useQuery is used without differential hooks
19
+ // for backwards compatibility.
20
+ export type Result<RowType> = QueryResult<RowType> | ReadonlyQueryResult<RowType>;
21
+
22
+ /**
23
+ * The configured state a {@link QueryRunner} is in.
24
+ *
25
+ * Creating these instances has no side effects (in particular, doesn't start database queries) and can be done in
26
+ * renders.
27
+ */
28
+ export type RunnerConfig<RowType> =
29
+ // No PowerSync database in context, reported as error.
30
+ | { kind: 'missing-db' }
31
+ // Query included sync streams that have not synced yet
32
+ | { kind: 'waiting-for-streams' }
33
+ | { kind: 'compile-error'; error: Error }
34
+ | QueryConfig<RowType>;
35
+
36
+ export interface QueryConfig<RowType> {
37
+ kind: 'query';
38
+ db: CommonPowerSyncDatabase;
39
+ query: WatchCompatibleQueryWithParams<RowType[]>;
40
+ sql: string;
41
+ parameters: ReadonlyArray<any>;
42
+ stringifiedParams: string; // For efficient comparisons
43
+ runOnce: boolean;
44
+ rowComparator: DifferentialWatchedQueryComparator<RowType> | undefined;
45
+ throttleMs: number | undefined;
46
+ reportFetching: boolean;
47
+ }
48
+
49
+ function configEquals<RowType>(a: RunnerConfig<RowType>, b: RunnerConfig<RowType>): boolean {
50
+ if (a === b) return true;
51
+
52
+ switch (a.kind) {
53
+ case 'missing-db':
54
+ case 'waiting-for-streams':
55
+ return a.kind == b.kind;
56
+ case 'compile-error':
57
+ // compile() runs on every render, so a failing query throws a new error each time.
58
+ return b.kind == 'compile-error' && a.error.message == b.error.message;
59
+ case 'query':
60
+ return (
61
+ b.kind == 'query' &&
62
+ a.db === b.db &&
63
+ a.sql == b.sql &&
64
+ a.stringifiedParams == b.stringifiedParams &&
65
+ a.runOnce == b.runOnce &&
66
+ // We don't compare rowComparator by reference, since it's typically an inline object changed on every rerender.
67
+ // Only toggling between differential and regular queries is considered a re-run worthy chamge.
68
+ !!a.rowComparator == !!b.rowComparator &&
69
+ a.throttleMs == b.throttleMs &&
70
+ a.reportFetching == b.reportFetching
71
+ );
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Returns a string identifying a query config, such that two configs have the same key if {@link configEquals} considers
77
+ * them equal (apart from the database, which callers are expected to scope keys to).
78
+ */
79
+ export function configKey<RowType>(config: QueryConfig<RowType>): string {
80
+ const { runOnce, rowComparator, throttleMs, reportFetching, sql, stringifiedParams } = config;
81
+ return JSON.stringify([runOnce, !!rowComparator, throttleMs ?? null, reportFetching, sql, stringifiedParams]);
82
+ }
83
+
84
+ /**
85
+ * For configs that can't run a query, returns the error to report.
86
+ */
87
+ export function configError<RowType>(config: Exclude<RunnerConfig<RowType>, QueryConfig<RowType>>): Error | null {
88
+ return idleResultFor(config).error ?? null;
89
+ }
90
+
91
+ const _loadingState: QueryResult<never> = { isLoading: true, isFetching: false, data: [], error: undefined };
92
+
93
+ function idleResultFor<RowType>(config: RunnerConfig<RowType>): Result<RowType> {
94
+ switch (config.kind) {
95
+ case 'missing-db':
96
+ return { isLoading: false, isFetching: false, data: [], error: new Error('PowerSync not configured.') };
97
+ case 'waiting-for-streams':
98
+ return _loadingState;
99
+ case 'compile-error':
100
+ return { isLoading: false, isFetching: false, data: [], error: config.error };
101
+ case 'query':
102
+ // Single queries always report fetching while they run.
103
+ const isFetching = config.runOnce || config.reportFetching;
104
+ return {
105
+ isLoading: true,
106
+ isFetching,
107
+ data: [],
108
+ error: undefined,
109
+ fetchReason: isFetching ? 'initial' : undefined
110
+ };
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Resolves the inputs of `useQuery` into a comparable {@link RunnerConfig}.
116
+ *
117
+ * This is pure (apart from compiling the query) and can run while rendering.
118
+ */
119
+ export function resolveConfig<RowType>(
120
+ db: CommonPowerSyncDatabase | null,
121
+ query: WatchCompatibleQueryWithParams<RowType[]>,
122
+ options: AdditionalOptions & DifferentialHookOptions<RowType>,
123
+ streamsHaveSynced: boolean
124
+ ): RunnerConfig<RowType> {
125
+ if (db == null) {
126
+ return { kind: 'missing-db' };
127
+ }
128
+ if (!streamsHaveSynced) {
129
+ return { kind: 'waiting-for-streams' };
130
+ }
131
+
132
+ let sql: string;
133
+ let parameters: ReadonlyArray<any>;
134
+ try {
135
+ const compiled = query.compile();
136
+ sql = compiled.sql;
137
+ parameters = compiled.parameters;
138
+ } catch (error) {
139
+ return { kind: 'compile-error', error: error as Error };
140
+ }
141
+
142
+ return {
143
+ kind: 'query',
144
+ db,
145
+ query,
146
+ sql,
147
+ parameters,
148
+ stringifiedParams: query.stringifiedParameters ?? JSON.stringify(parameters),
149
+ runOnce: options.runQueryOnce == true,
150
+ rowComparator: options.rowComparator,
151
+ throttleMs: options.throttleMs,
152
+ reportFetching: options.reportFetching ?? true
153
+ };
154
+ }
155
+
156
+ export interface QueryRunnerListener extends BaseListener {
157
+ onChange(): void;
158
+ }
159
+
160
+ /**
161
+ * An imperative store backing the `useQuery` hook. There is always one instance of this per `useQuery` hook.
162
+ *
163
+ * On every render, {@link resultFor} checks for config changes and returns the current result. Configuration changes
164
+ * are not applied during renders. Instead, {@link configure} is used to apply configuration changes in a commit. This
165
+ * ensures multiple {@link resultFor} calls in uncommited renders are cheap and don't trigger queries.
166
+ *
167
+ * Work is only active while at least one listener is registered.
168
+ */
169
+ export class QueryRunner<RowType> extends BaseObserver<QueryRunnerListener> {
170
+ private config: RunnerConfig<RowType> | null = null;
171
+ private idleResult: Result<RowType> = _loadingState;
172
+ /**
173
+ * The active work, only non-null while we have listeners.
174
+ */
175
+ private work: QueryWork<RowType> | null = null;
176
+ /**
177
+ * A cached result for a config that hasn't been applied yet, so that repeated renders return a stable object.
178
+ */
179
+ private uncommitedConfigChange: {
180
+ config: RunnerConfig<RowType>;
181
+ snapshot: Result<RowType>;
182
+ result: Result<RowType>;
183
+ isOptimisticStateChange: boolean;
184
+ } | null = null;
185
+
186
+ readonly subscribe = (onChange: () => void): (() => void) => {
187
+ const listener = { onChange } satisfies QueryRunnerListener;
188
+
189
+ const unregister = this.registerListener(listener);
190
+ if (this.listeners.size == 1) {
191
+ this.startWork();
192
+ this.notifyListeners();
193
+ }
194
+
195
+ return () => {
196
+ unregister();
197
+ if (this.listeners.size == 0) {
198
+ this.work?.dispose();
199
+ this.work = null;
200
+ }
201
+ };
202
+ };
203
+
204
+ readonly getSnapshot = (): Result<RowType> => {
205
+ return this.work?.result ?? this.idleResult;
206
+ };
207
+
208
+ /**
209
+ * Returns the result to render for the given config, without changing the runner.
210
+ *
211
+ * If the config has already been applied, this is the current snapshot. Otherwise, it's the result we expect to
212
+ * report right after {@link configure} applies it, so that changed inputs are reflected in the same render (even if
213
+ * that render is ultimately dropped).
214
+ */
215
+ resultFor(config: RunnerConfig<RowType>, snapshot: Result<RowType>): Result<RowType> {
216
+ if (this.config != null && configEquals(this.config, config)) {
217
+ return snapshot;
218
+ }
219
+
220
+ const pending = this.uncommitedConfigChange;
221
+ if (pending != null && pending.snapshot === snapshot && configEquals(pending.config, config)) {
222
+ return pending.result;
223
+ }
224
+
225
+ // A re-render has changed the query, and we'll start running that query in a useEffect hook calling configure.
226
+ // For now, optimistically return the loading state that query would start.
227
+ const fromWork = this.work?.pendingResultFor(config);
228
+ const result = fromWork ?? idleResultFor(config);
229
+ this.uncommitedConfigChange = { config, snapshot, result, isOptimisticStateChange: fromWork == null };
230
+ return result;
231
+ }
232
+
233
+ /**
234
+ * Applies the inputs of a committed render to this runner. This does nothing if they haven't changed.
235
+ *
236
+ * This modifies state and should not run during a render.
237
+ *
238
+ * `initial` can be an existing result from another runner. This is used for one-shot suspense queries where state is
239
+ * only shared in the initial loading state and then forked to give each component an independent runner.
240
+ */
241
+ configure(next: RunnerConfig<RowType>, initial?: Result<RowType>) {
242
+ if (this.config != null && configEquals(this.config, next)) {
243
+ return;
244
+ }
245
+
246
+ const pending = this.uncommitedConfigChange;
247
+ this.config = next;
248
+ this.idleResult = initial
249
+ ? initial
250
+ : pending != null && pending.isOptimisticStateChange && configEquals(pending.config, next)
251
+ ? // We already returned this as an optimistic state in a previous resultFor call. Use the same result to not
252
+ // cause another render.
253
+ pending.result
254
+ : idleResultFor(next);
255
+ this.uncommitedConfigChange = null;
256
+
257
+ if (this.work == null || !this.work.tryUpdate(next)) {
258
+ this.work?.dispose();
259
+ this.work = null;
260
+ if (this.listeners.size > 0) {
261
+ this.startWork();
262
+ }
263
+ }
264
+
265
+ this.notifyListeners();
266
+ }
267
+
268
+ private startWork() {
269
+ const config = this.config;
270
+ if (config == null || config.kind != 'query') {
271
+ // In waiting or error state, don't run anything.
272
+ return;
273
+ }
274
+
275
+ const emit = () => this.notifyListeners();
276
+ this.work = new (config.runOnce ? SingleQueryWork : WatchedQueryWork)(config, this.idleResult, emit);
277
+ }
278
+
279
+ private notifyListeners() {
280
+ this.iterateListeners((l) => l.onChange?.());
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Active work to run a query (once or watched).
286
+ */
287
+ interface QueryWork<RowType> {
288
+ readonly result: Result<RowType>;
289
+ /**
290
+ * If {@link tryUpdate} would accept the config, returns the result to report until it's applied. Must be pure.
291
+ */
292
+ pendingResultFor(config: RunnerConfig<RowType>): Result<RowType> | null;
293
+ /**
294
+ * Attempts to apply the new config to this work without restarting it.
295
+ */
296
+ tryUpdate(config: RunnerConfig<RowType>): boolean;
297
+ dispose(): void;
298
+ }
299
+
300
+ class SingleQueryWork<RowType> implements QueryWork<RowType> {
301
+ result: QueryResult<RowType>;
302
+ private abortController: AbortController | null = null;
303
+ private disposed = false;
304
+
305
+ constructor(
306
+ private readonly config: QueryConfig<RowType>,
307
+ initial: Result<RowType>,
308
+ private readonly emit: () => void
309
+ ) {
310
+ if (!initial.isLoading && initial.error == null) {
311
+ // Seeded with an existing result, no need to run it again.
312
+ this.result = { ...(initial as QueryResult<RowType>), refresh: this.refresh };
313
+ return;
314
+ }
315
+
316
+ const fetchReason = 'initial';
317
+ this.result = {
318
+ ...(initial as QueryResult<RowType>),
319
+ isFetching: true,
320
+ fetchReason,
321
+ refresh: this.refresh
322
+ };
323
+ this.run(fetchReason);
324
+ }
325
+
326
+ readonly refresh = async (signal?: AbortSignal) => {
327
+ if (this.disposed) return;
328
+ await this.run('refresh', signal);
329
+ };
330
+
331
+ private setResult(update: Partial<QueryResult<RowType>>) {
332
+ this.result = { ...this.result, ...update };
333
+ this.emit();
334
+ }
335
+
336
+ private async run(fetchReason: FetchReason, outerSignal?: AbortSignal) {
337
+ this.abortController?.abort();
338
+ const controller = (this.abortController = new AbortController());
339
+ const signal = controller.signal;
340
+ const isAborted = () => signal.aborted || outerSignal?.aborted == true;
341
+
342
+ if (!this.result.isLoading || this.result.error) {
343
+ // After an error, data is empty, so we're loading again rather than refreshing existing rows.
344
+ const isLoading = fetchReason === 'initial' || this.result.error != null;
345
+ this.setResult({ isLoading, isFetching: true, error: undefined, fetchReason });
346
+ }
347
+
348
+ const { query, sql, parameters, db } = this.config;
349
+ try {
350
+ const data = await query.execute({ sql, parameters: [...parameters], db });
351
+ if (isAborted()) return;
352
+ this.setResult({ isLoading: false, isFetching: false, data, error: undefined, fetchReason: undefined });
353
+ } catch (error) {
354
+ if (isAborted()) return;
355
+ this.setResult({ isLoading: false, isFetching: false, data: [], error: error as Error, fetchReason: undefined });
356
+ }
357
+ }
358
+
359
+ pendingResultFor(): null {
360
+ return null;
361
+ }
362
+
363
+ tryUpdate(): boolean {
364
+ return false;
365
+ }
366
+
367
+ dispose(): void {
368
+ this.abortController?.abort();
369
+ this.abortController = null;
370
+ this.disposed = true;
371
+ }
372
+ }
373
+
374
+ class WatchedQueryWork<RowType> implements QueryWork<RowType> {
375
+ result: Result<RowType>;
376
+ private readonly watch: DifferentialWatchedQuery<RowType>;
377
+ private readonly disposeListener: () => void;
378
+ /**
379
+ * Set after calling `updateSettings` until the watched query starts applying the new settings. We report
380
+ * `isFetching` in the meantime so that the hook doesn't briefly appear settled with stale data.
381
+ */
382
+ private pendingUpdate = false;
383
+ /**
384
+ * Set by {@link tryUpdate} until the updated query has produced its first result. Until then, `data` still holds the
385
+ * previous query's rows, which is reported as `fetchReason: 'settings-changed'`.
386
+ */
387
+ private awaitingUpdatedResult = false;
388
+ private reportFetching: boolean;
389
+
390
+ constructor(
391
+ private config: QueryConfig<RowType>,
392
+ initial: Result<RowType>,
393
+ private readonly emit: () => void
394
+ ) {
395
+ this.result = initial;
396
+ this.reportFetching = config.reportFetching;
397
+
398
+ const { db, query, rowComparator, throttleMs, reportFetching } = config;
399
+ const customQuery = db.customQuery(query);
400
+ this.watch = rowComparator
401
+ ? customQuery.differentialWatch({ rowComparator, reportFetching, throttleMs })
402
+ : customQuery.watch({ reportFetching, throttleMs });
403
+
404
+ this.disposeListener = this.watch.registerListener({
405
+ onStateChange: (state) => {
406
+ if (this.awaitingUpdatedResult && !this.pendingUpdate && !state.isFetching) {
407
+ // The first completed fetch after the new settings were applied is the updated query's result.
408
+ this.awaitingUpdatedResult = false;
409
+ }
410
+ this.result = this.mapState(state);
411
+ this.emit();
412
+ },
413
+ settingsWillUpdate: () => {
414
+ // The watched query sets isFetching itself after this event, so we stop overriding it. We don't emit
415
+ // here because the state may not reflect that yet, the next onStateChange delivers the updated state.
416
+ this.pendingUpdate = false;
417
+ }
418
+ });
419
+ }
420
+
421
+ private mapState(state: WatchedQueryState<ReadonlyArray<Readonly<RowType>>>): Result<RowType> {
422
+ // The state object may be mutated by the watched query, so we copy it into a fresh snapshot.
423
+ const isFetching = state.isFetching || (this.pendingUpdate && this.reportFetching);
424
+ return {
425
+ data: state.data as RowType[],
426
+ isLoading: state.isLoading,
427
+ isFetching,
428
+ error: state.error ?? undefined,
429
+ fetchReason: this.fetchReasonFor(state.isLoading, isFetching)
430
+ };
431
+ }
432
+
433
+ private fetchReasonFor(isLoading: boolean, isFetching: boolean): FetchReason | undefined {
434
+ if (!isFetching) return undefined;
435
+ if (isLoading) return 'initial';
436
+ return this.awaitingUpdatedResult ? 'settings-changed' : 'tables-changed';
437
+ }
438
+
439
+ private canUpdate(config: RunnerConfig<RowType>): config is QueryConfig<RowType> {
440
+ return (
441
+ config.kind == 'query' &&
442
+ !config.runOnce &&
443
+ config.db === this.config.db &&
444
+ !!config.rowComparator == !!this.config.rowComparator
445
+ );
446
+ }
447
+
448
+ pendingResultFor(config: RunnerConfig<RowType>): Result<RowType> | null {
449
+ if (!this.canUpdate(config)) {
450
+ return null;
451
+ }
452
+
453
+ // Keep the previous data while the updated query runs.
454
+ const isFetching = this.result.isFetching || config.reportFetching;
455
+ return {
456
+ ...this.result,
457
+ isFetching,
458
+ fetchReason: !isFetching ? undefined : this.result.isLoading ? 'initial' : 'settings-changed'
459
+ };
460
+ }
461
+
462
+ tryUpdate(config: RunnerConfig<RowType>): boolean {
463
+ if (!this.canUpdate(config)) {
464
+ return false;
465
+ }
466
+
467
+ this.config = config;
468
+ this.reportFetching = config.reportFetching;
469
+ this.pendingUpdate = true;
470
+ this.awaitingUpdatedResult = true;
471
+ this.watch.updateSettings({
472
+ query: config.query,
473
+ throttleMs: config.throttleMs,
474
+ reportFetching: config.reportFetching
475
+ });
476
+ this.result = this.mapState(this.watch.state);
477
+ return true;
478
+ }
479
+
480
+ dispose(): void {
481
+ this.disposeListener();
482
+ this.watch.close();
483
+ }
484
+ }