@powersync-bridge/react 0.0.1-alpha.0 → 0.0.1-alpha.2

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/README.md CHANGED
@@ -1,24 +1,115 @@
1
1
  # powersync-bridge
2
2
 
3
- A client-side bridge between a [PowerSync](https://powersync.com) local SQLite database and a
4
- conventional HTTP API, for web and React Native.
5
-
6
- The right data source, local synced SQLite or the live API, is a runtime, per-screen decision.
7
- This package makes it automatic:
8
-
9
- - **`useRacedList`** — paint the first screen from whichever source is *correct* first. A
10
- first-ever visit has an empty local table; a warm re-mount has yesterday's checkpoint. The
11
- bridge fetches one API snapshot, merges by id with pending-write and freshness awareness,
12
- and hands the list to local sync as soon as local is fresh in this session.
13
- - **`useInfiniteList`** — scroll past the synced window. Older data arrives either through
14
- PowerSync sync streams (one equality partition at a time, bounded) or through your API's
15
- pages. Row removals are classified as filtered-out, delete, or eviction, so the list never
16
- resurrects deletes and never loses content mid-scroll.
17
- - **`useOnDemandStream`** — pull one record into the offline database by id.
18
-
19
- Status: **v0 alpha**. Core engine and invariant tests are complete (35 tests on a virtual-time
20
- fake driver); the PowerSync driver is written against `@powersync/common` 2.3 and needs a running
21
- integration before GA. Sizes (minified + gzip): core 8.2 kB, React 0.6 kB, driver 1.8 kB.
3
+ Local SQLite and your HTTP API, behind one list interface for React and React Native.
4
+
5
+ The application defines its SQL, API calls, filters and permissions. The bridge owns racing,
6
+ pagination, pending-write protection, reconciliation, subscriptions, connectivity, retries and
7
+ bounded memory. API results stay in memory; only PowerSync makes records durable offline.
8
+
9
+ ## Start with `useInfiniteQuery`
10
+
11
+ ```tsx
12
+ import { useInfiniteQuery } from '@powersync-bridge/react';
13
+
14
+ type Transaction = { id: string; date: string; amount: string };
15
+
16
+ const transactions = useInfiniteQuery<Transaction>({
17
+ queryKey: ['transactions', organizationId, filters, permissionVersion],
18
+ orderBy: ['date', 'id'],
19
+ // Descending order, 25 rows per page and a 500-row memory window are defaults.
20
+ query: ({ cursor, limit }) =>
21
+ db.select().from(transaction)
22
+ .where(and(
23
+ eq(transaction.organizationId, organizationId),
24
+ cursor ? or(
25
+ lt(transaction.date, cursor.date),
26
+ and(eq(transaction.date, cursor.date), lt(transaction.id, cursor.id)),
27
+ ) : undefined,
28
+ ))
29
+ .orderBy(desc(transaction.date), desc(transaction.id))
30
+ .limit(limit),
31
+ fetchPage: async ({ cursor, limit, signal }) =>
32
+ api.transactions.list({ organizationId, filters,
33
+ cursor: cursor ? { date: cursor.date, id: cursor.id } : undefined,
34
+ limit, signal,
35
+ }),
36
+ });
37
+
38
+ // FlatList / virtualized list:
39
+ // data={transactions.data}
40
+ // onEndReached={() => transactions.hasNextPage && transactions.fetchNextPage()}
41
+ // refreshing={transactions.isFetching}
42
+ // onRefresh={transactions.refresh}
43
+ ```
44
+
45
+ The local and API rows must have the same decoded shape and a strict, stable sort order.
46
+ Honor the requested `limit`: the bridge requests one extra row to detect another page.
47
+ `cursor` is the previous API row, never a cursor guessed from a sparse local feed. Local reads
48
+ can fill a requested page while its API request is still pending. Every requested page races;
49
+ API requests follow a single cursor chain, including when scrolling outpaces the network.
50
+
51
+ `data` contains ordinary rows. `items` additionally exposes each row's source and local presence
52
+ for edit guards. `error` reports an error preventing the requested range from being filled;
53
+ `errors` retains independent local/API diagnostics even when usable rows are displayed.
54
+ `retry()` retries the pending range. `refresh()` / `refetch()` starts again at the current window.
55
+ At `maxRows`, `needsOlderWindow` becomes true when more history may exist; `continueOlder()`
56
+ opens the next bounded window. Changing `queryKey` discards the previous scope.
57
+
58
+ Include every organization, filter and permission predicate in `queryKey`; the bridge does not
59
+ invent business authorization. It infers the business table for single-table queries. Supply `table`
60
+ for joins or ambiguous queries, or `getRowIdentity(row) => ({ table, id })` for a heterogeneous feed whose display
61
+ IDs differ from the underlying business IDs.
62
+
63
+ `mapQuery(builder, decode)` preserves ORM metadata when decoding rows. `rawQuery(db,
64
+ { text, params }, tables, decode)` supports parameterized SQL feeds with explicit source tables.
65
+ Both come from `@powersync-bridge/drizzle`; no application adapter or custom watch is needed.
66
+
67
+ ## Connectivity
68
+
69
+ Browser connectivity is observed automatically. In React Native, pass the existing network
70
+ hook's boolean once at the provider:
71
+
72
+ ```tsx
73
+ <BridgeProvider bridge={bridge} online={online}>
74
+ <App />
75
+ </BridgeProvider>
76
+ ```
77
+
78
+ `online` is optional and may be `undefined`. The bridge also handles HTTP failures when a
79
+ connectivity hint incorrectly says online. A disconnected sync socket does not by itself mean
80
+ the API is unavailable. Downloaded rows continue to paginate offline; additional archive rows
81
+ require a connection. Reconnection resumes the pending API range without clearing visible rows.
82
+
83
+ The lower-level `useRacedList`, `useInfiniteList`, `useOnDemandStream` and `useAutoSync` APIs
84
+ remain available for specialized workflows. Ordinary paginated lists need only `useInfiniteQuery`.
85
+
86
+ ## Hidden screens and checkpoint bursts
87
+
88
+ Wrap a retained screen or tab in `BridgeActivity` and pass its existing visibility state:
89
+
90
+ ```tsx
91
+ import { BridgeActivity } from '@powersync-bridge/react';
92
+
93
+ <BridgeActivity active={isVisible}>
94
+ <ServicesScreen />
95
+ </BridgeActivity>
96
+ ```
97
+
98
+ This applies to `useInfiniteQuery` and `useRacedList`. Pausing stops their SQLite watches,
99
+ checkpoint reads and pending API requests while keeping the last result and loaded page window.
100
+ Returning refreshes the local baseline, including rows changed or deleted while hidden.
101
+ An active consumer elsewhere keeps a shared query running. Nested boundaries cannot reactivate
102
+ an inactive parent. Identity, permissions and query-key changes still clear the outgoing scope.
103
+ Use `enabled` for query eligibility and `BridgeActivity` for temporary screen visibility.
104
+ On-demand sync streams and uploads continue independently.
105
+
106
+ Checkpoint refreshes are single-flight per observer. A synchronous burst produces one read;
107
+ changes during that read produce one follow-up, and superseded results cannot claim freshness.
108
+ Checkpoint maintenance shares one background-read slot across the bridge; first reads and
109
+ pagination bypass that queue. Queued maintenance is cancelled when its observer pauses.
110
+ Unscoped queries refresh only for global checkpoints. A query declaring `stream` also refreshes
111
+ for its own stream, rather than every unrelated stream. Closing a watch cancels its queued
112
+ follow-up. Applications need no checkpoint debounce, refresh queue or cache workaround.
22
113
 
23
114
  ## What your backend must change
24
115
 
@@ -39,7 +130,7 @@ alignment, not a change: your list endpoint sorts rows the same way your local q
39
130
  pnpm add powersync-bridge @powersync-bridge/react @powersync-bridge/drizzle @powersync-bridge/powersync
40
131
  ```
41
132
 
42
- Peers: `@powersync/common ^2.3`, `@powersync/web ^2.4` or `@powersync/react-native ^2.3`,
133
+ Peers: `@powersync/common ^1.57.3 || ^2.3`, with your compatible web or native SDK,
43
134
  `@powersync/drizzle-driver`, `drizzle-orm`, `react ^18.2 || ^19`. TanStack Query is optional.
44
135
 
45
136
  ## Setup (once, in a plain module)
package/dist/index.cjs CHANGED
@@ -20,40 +20,87 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
+ BridgeActivity: () => BridgeActivity,
23
24
  BridgeProvider: () => BridgeProvider,
24
25
  useAutoSync: () => useAutoSync,
25
26
  useBridge: () => useBridge,
26
27
  useInfiniteList: () => useInfiniteList,
28
+ useInfiniteQuery: () => useInfiniteQuery,
27
29
  useOnDemandStream: () => useOnDemandStream,
28
30
  useRacedList: () => useRacedList
29
31
  });
30
32
  module.exports = __toCommonJS(src_exports);
31
33
  var import_react = require("react");
34
+ var import_powersync_bridge = require("powersync-bridge");
32
35
  var BridgeContext = (0, import_react.createContext)(null);
33
- function BridgeProvider({ bridge, children }) {
36
+ var BridgeActivityContext = (0, import_react.createContext)(true);
37
+ var BridgeActivity = ({ active, children }) => {
38
+ const parentActive = (0, import_react.useContext)(BridgeActivityContext);
39
+ return (0, import_react.createElement)(BridgeActivityContext.Provider, { value: parentActive && active }, children);
40
+ };
41
+ function BridgeProvider({ bridge, children, online }) {
42
+ (0, import_react.useEffect)(() => {
43
+ bridge.setOnline(online);
44
+ }, [bridge, online]);
34
45
  return (0, import_react.createElement)(BridgeContext.Provider, { value: bridge }, children);
35
46
  }
47
+ var useInfiniteQuery = (options) => {
48
+ const bridge = useBridge();
49
+ const active = (0, import_react.useContext)(BridgeActivityContext);
50
+ const epoch = useEpoch(bridge);
51
+ const key = (0, import_powersync_bridge.infiniteQueryKey)(options);
52
+ const controller = (0, import_react.useMemo)(() => bridge.query(options), [bridge, epoch, key]);
53
+ (0, import_react.useEffect)(() => {
54
+ controller.retain(active);
55
+ return () => controller.release(active);
56
+ }, [controller, active]);
57
+ const result = (0, import_react.useSyncExternalStore)(
58
+ controller.store.subscribe,
59
+ controller.store.getSnapshot,
60
+ controller.store.getSnapshot
61
+ );
62
+ return (0, import_react.useMemo)(
63
+ () => ({
64
+ ...result,
65
+ fetchNextPage: controller.fetchNextPage,
66
+ retry: controller.retry,
67
+ refresh: controller.refresh,
68
+ refetch: controller.refresh,
69
+ continueOlder: controller.continueOlder
70
+ }),
71
+ [result, controller]
72
+ );
73
+ };
36
74
  function useBridge() {
37
75
  const b = (0, import_react.useContext)(BridgeContext);
38
76
  if (!b) throw new Error("powersync-bridge: no <BridgeProvider> above this component");
39
77
  return b;
40
78
  }
41
79
  function useEpoch(bridge) {
42
- return (0, import_react.useSyncExternalStore)(bridge.epochStore.subscribe, bridge.epochStore.getSnapshot, bridge.epochStore.getSnapshot);
80
+ return (0, import_react.useSyncExternalStore)(
81
+ bridge.epochStore.subscribe,
82
+ bridge.epochStore.getSnapshot,
83
+ bridge.epochStore.getSnapshot
84
+ );
43
85
  }
44
- function useRetained(bridge, key, acquire) {
86
+ function useRetained(bridge, key, acquire, active = true) {
45
87
  const epoch = useEpoch(bridge);
46
88
  const holder = (0, import_react.useMemo)(() => acquire(), [bridge, epoch, key]);
47
89
  (0, import_react.useEffect)(() => {
48
- holder.retain();
49
- return () => holder.release();
50
- }, [holder]);
51
- return (0, import_react.useSyncExternalStore)(holder.store.subscribe, holder.store.getSnapshot, holder.store.getSnapshot);
90
+ holder.retain(active);
91
+ return () => holder.release(active);
92
+ }, [holder, active]);
93
+ return (0, import_react.useSyncExternalStore)(
94
+ holder.store.subscribe,
95
+ holder.store.getSnapshot,
96
+ holder.store.getSnapshot
97
+ );
52
98
  }
53
99
  function useRacedList(def, scope) {
54
100
  const bridge = useBridge();
101
+ const active = (0, import_react.useContext)(BridgeActivityContext);
55
102
  const key = `${def.id}:${JSON.stringify(scope ?? null)}`;
56
- return useRetained(bridge, key, () => bridge.raced(def, scope));
103
+ return useRetained(bridge, key, () => bridge.raced(def, scope), active);
57
104
  }
58
105
  function useInfiniteList(def, scope) {
59
106
  const bridge = useBridge();
@@ -64,7 +111,11 @@ function useInfiniteList(def, scope) {
64
111
  store.retain();
65
112
  return () => store.release();
66
113
  }, [store]);
67
- const result = (0, import_react.useSyncExternalStore)(store.store.subscribe, store.store.getSnapshot, store.store.getSnapshot);
114
+ const result = (0, import_react.useSyncExternalStore)(
115
+ store.store.subscribe,
116
+ store.store.getSnapshot,
117
+ store.store.getSnapshot
118
+ );
68
119
  return (0, import_react.useMemo)(
69
120
  () => ({ ...result, loadMore: () => void store.loadMore(), retry: () => void store.retry() }),
70
121
  [result, store]
@@ -82,10 +133,12 @@ function useAutoSync(config, ids) {
82
133
  }
83
134
  // Annotate the CommonJS export names for ESM import in node:
84
135
  0 && (module.exports = {
136
+ BridgeActivity,
85
137
  BridgeProvider,
86
138
  useAutoSync,
87
139
  useBridge,
88
140
  useInfiniteList,
141
+ useInfiniteQuery,
89
142
  useOnDemandStream,
90
143
  useRacedList
91
144
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createContext, createElement, useContext, useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react';\nimport type {\n Bridge,\n FlaggerConfig,\n FlagResult,\n InfiniteListDefinition,\n InfiniteListResult,\n OnDemandOptions,\n OnDemandResult,\n OrderKey,\n Params,\n RacedListDefinition,\n RacedListResult,\n Store,\n} from 'powersync-bridge';\n\n// NOTE (R11, static assertion): this package never imports `useQuery` from TanStack.\n// It renders from the engine store via useSyncExternalStore only.\n\nconst BridgeContext = createContext<Bridge | null>(null);\n\nexport interface BridgeProviderProps {\n bridge: Bridge;\n children?: ReactNode;\n}\n\n/** Mount once at app root. Crud-delta observation started at createBridge(), not here (F6-001). */\nexport function BridgeProvider({ bridge, children }: BridgeProviderProps) {\n return createElement(BridgeContext.Provider, { value: bridge }, children);\n}\n\nexport function useBridge(): Bridge {\n const b = useContext(BridgeContext);\n if (!b) throw new Error('powersync-bridge: no <BridgeProvider> above this component');\n return b;\n}\n\nfunction useEpoch(bridge: Bridge): number {\n return useSyncExternalStore(bridge.epochStore.subscribe, bridge.epochStore.getSnapshot, bridge.epochStore.getSnapshot);\n}\n\ninterface Retainable<S> {\n readonly store: Store<S>;\n retain(): void;\n release(): void;\n}\n\n/**\n * Acquire a ref-counted store for the current epoch and subscribe to it. Retain/release run in\n * an effect so StrictMode's double-invoke is a no-op pair (R10); the store is shared across\n * components that ask for the same definition + scope.\n */\nfunction useRetained<S>(bridge: Bridge, key: string, acquire: () => Retainable<S>): S {\n const epoch = useEpoch(bridge);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const holder = useMemo(() => acquire(), [bridge, epoch, key]);\n useEffect(() => {\n holder.retain();\n return () => holder.release();\n }, [holder]);\n return useSyncExternalStore(holder.store.subscribe, holder.store.getSnapshot, holder.store.getSnapshot);\n}\n\nexport function useRacedList<TItem, TScope, TApi, K extends OrderKey<TItem>>(\n def: RacedListDefinition<TItem, TScope, TApi, K>,\n scope: TScope,\n): RacedListResult<TItem> {\n const bridge = useBridge();\n const key = `${def.id}:${JSON.stringify(scope ?? null)}`;\n return useRetained(bridge, key, () => bridge.raced(def, scope));\n}\n\nexport interface UseInfiniteListResult<TItem> extends InfiniteListResult<TItem> {\n loadMore(): void;\n /** Clears API backoff and loads (R16). */\n retry(): void;\n}\n\nexport function useInfiniteList<TItem, TScope, K extends OrderKey<TItem>, TCursor, TPartition>(\n def: InfiniteListDefinition<TItem, TScope, K, TCursor, TPartition>,\n scope: TScope,\n): UseInfiniteListResult<TItem> {\n const bridge = useBridge();\n const epoch = useEpoch(bridge);\n const key = `${def.id}:${JSON.stringify(scope ?? null)}`;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const store = useMemo(() => bridge.infinite(def, scope), [bridge, epoch, key]);\n useEffect(() => {\n store.retain();\n return () => store.release();\n }, [store]);\n const result = useSyncExternalStore(store.store.subscribe, store.store.getSnapshot, store.store.getSnapshot);\n return useMemo(\n () => ({ ...result, loadMore: () => void store.loadMore(), retry: () => void store.retry() }),\n [result, store],\n );\n}\n\n/** The default \"pull one row into the offline DB\" primitive (§7). */\nexport function useOnDemandStream(name: string, params: Params | null, opts: OnDemandOptions = {}): OnDemandResult {\n const bridge = useBridge();\n const key = `${name}:${JSON.stringify(params)}:${JSON.stringify(opts)}`;\n return useRetained(bridge, key, () => bridge.onDemand(name, params, opts));\n}\n\n/** OPTIONAL: server-side flagging (§7). Prefer useOnDemandStream. */\nexport function useAutoSync(config: FlaggerConfig, ids: readonly string[]): FlagResult {\n const bridge = useBridge();\n const key = `${config.stream}:${JSON.stringify([...ids].sort())}`;\n return useRetained(bridge, key, () => bridge.autoSync(config, ids));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAmH;AAmBnH,IAAM,oBAAgB,4BAA6B,IAAI;AAQhD,SAAS,eAAe,EAAE,QAAQ,SAAS,GAAwB;AACxE,aAAO,4BAAc,cAAc,UAAU,EAAE,OAAO,OAAO,GAAG,QAAQ;AAC1E;AAEO,SAAS,YAAoB;AAClC,QAAM,QAAI,yBAAW,aAAa;AAClC,MAAI,CAAC,EAAG,OAAM,IAAI,MAAM,4DAA4D;AACpF,SAAO;AACT;AAEA,SAAS,SAAS,QAAwB;AACxC,aAAO,mCAAqB,OAAO,WAAW,WAAW,OAAO,WAAW,aAAa,OAAO,WAAW,WAAW;AACvH;AAa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,GAAG,IAAI,IAAI,KAAK,UAAU,MAAM,CAAC,IAAI,KAAK,UAAU,IAAI,CAAC;AACrE,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,SAAS,MAAM,QAAQ,IAAI,CAAC;AAC3E;AAGO,SAAS,YAAY,QAAuB,KAAoC;AACrF,QAAM,SAAS,UAAU;AACzB,QAAM,MAAM,GAAG,OAAO,MAAM,IAAI,KAAK,UAAU,CAAC,GAAG,GAAG,EAAE,KAAK,CAAC,CAAC;AAC/D,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,SAAS,QAAQ,GAAG,CAAC;AACpE;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n createContext,\n createElement,\n useContext,\n useEffect,\n useMemo,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport { infiniteQueryKey } from 'powersync-bridge';\nimport type {\n Bridge,\n FlaggerConfig,\n FlagResult,\n InfiniteListDefinition,\n InfiniteListResult,\n InfiniteQueryOptions,\n InfiniteQueryResult,\n OnDemandOptions,\n OnDemandResult,\n OrderKey,\n Params,\n RacedListDefinition,\n RacedListResult,\n Store,\n} from 'powersync-bridge';\n\n// NOTE (R11, static assertion): this package never imports `useQuery` from TanStack.\n// It renders from the engine store via useSyncExternalStore only.\n\nconst BridgeContext = createContext<Bridge | null>(null);\nconst BridgeActivityContext = createContext(true);\n\n/** Pause read observers in a hidden subtree while retaining their scoped snapshots. */\nexport const BridgeActivity = ({ active, children }: { active: boolean; children?: ReactNode }) => {\n const parentActive = useContext(BridgeActivityContext);\n return createElement(BridgeActivityContext.Provider, { value: parentActive && active }, children);\n};\n\nexport interface BridgeProviderProps {\n bridge: Bridge;\n children?: ReactNode;\n /** Native apps supply their network hook's result once, at the provider. */\n online?: boolean | undefined;\n}\n\n/** Mount once at app root. Crud-delta observation started at createBridge(), not here (F6-001). */\nexport function BridgeProvider({ bridge, children, online }: BridgeProviderProps) {\n useEffect(() => {\n bridge.setOnline(online);\n }, [bridge, online]);\n return createElement(BridgeContext.Provider, { value: bridge }, children);\n}\n\nexport type UseInfiniteQueryResult<T> = InfiniteQueryResult<T> & {\n fetchNextPage(): void;\n retry(): void;\n refresh(): void;\n refetch(): void;\n continueOlder(): void;\n};\n\n/** Define local SQL and an API page; the bridge owns all paging and reconciliation. */\nexport const useInfiniteQuery = <T extends { id: string }>(\n options: InfiniteQueryOptions<T>,\n): UseInfiniteQueryResult<T> => {\n const bridge = useBridge();\n const active = useContext(BridgeActivityContext);\n const epoch = useEpoch(bridge);\n const key = infiniteQueryKey(options);\n // Definitions are closures; every changing predicate belongs in queryKey.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const controller = useMemo(() => bridge.query(options), [bridge, epoch, key]);\n useEffect(() => {\n controller.retain(active);\n return () => controller.release(active);\n }, [controller, active]);\n const result = useSyncExternalStore(\n controller.store.subscribe,\n controller.store.getSnapshot,\n controller.store.getSnapshot,\n );\n return useMemo(\n () => ({\n ...result,\n fetchNextPage: controller.fetchNextPage,\n retry: controller.retry,\n refresh: controller.refresh,\n refetch: controller.refresh,\n continueOlder: controller.continueOlder,\n }),\n [result, controller],\n );\n};\n\nexport function useBridge(): Bridge {\n const b = useContext(BridgeContext);\n if (!b) throw new Error('powersync-bridge: no <BridgeProvider> above this component');\n return b;\n}\n\nfunction useEpoch(bridge: Bridge): number {\n return useSyncExternalStore(\n bridge.epochStore.subscribe,\n bridge.epochStore.getSnapshot,\n bridge.epochStore.getSnapshot,\n );\n}\n\ninterface Retainable<S> {\n readonly store: Store<S>;\n retain(active?: boolean): void;\n release(active?: boolean): void;\n}\n\n/**\n * Acquire a ref-counted store for the current epoch and subscribe to it. Retain/release run in\n * an effect so StrictMode's double-invoke is a no-op pair (R10); the store is shared across\n * components that ask for the same definition + scope.\n */\nfunction useRetained<S>(\n bridge: Bridge,\n key: string,\n acquire: () => Retainable<S>,\n active = true,\n): S {\n const epoch = useEpoch(bridge);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const holder = useMemo(() => acquire(), [bridge, epoch, key]);\n useEffect(() => {\n holder.retain(active);\n return () => holder.release(active);\n }, [holder, active]);\n return useSyncExternalStore(\n holder.store.subscribe,\n holder.store.getSnapshot,\n holder.store.getSnapshot,\n );\n}\n\nexport function useRacedList<TItem, TScope, TApi, K extends OrderKey<TItem>>(\n def: RacedListDefinition<TItem, TScope, TApi, K>,\n scope: TScope,\n): RacedListResult<TItem> {\n const bridge = useBridge();\n const active = useContext(BridgeActivityContext);\n const key = `${def.id}:${JSON.stringify(scope ?? null)}`;\n return useRetained(bridge, key, () => bridge.raced(def, scope), active);\n}\n\nexport interface UseInfiniteListResult<TItem> extends InfiniteListResult<TItem> {\n loadMore(): void;\n /** Clears API backoff and loads (R16). */\n retry(): void;\n}\n\nexport function useInfiniteList<TItem, TScope, K extends OrderKey<TItem>, TCursor, TPartition>(\n def: InfiniteListDefinition<TItem, TScope, K, TCursor, TPartition>,\n scope: TScope,\n): UseInfiniteListResult<TItem> {\n const bridge = useBridge();\n const epoch = useEpoch(bridge);\n const key = `${def.id}:${JSON.stringify(scope ?? null)}`;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const store = useMemo(() => bridge.infinite(def, scope), [bridge, epoch, key]);\n useEffect(() => {\n store.retain();\n return () => store.release();\n }, [store]);\n const result = useSyncExternalStore(\n store.store.subscribe,\n store.store.getSnapshot,\n store.store.getSnapshot,\n );\n return useMemo(\n () => ({ ...result, loadMore: () => void store.loadMore(), retry: () => void store.retry() }),\n [result, store],\n );\n}\n\n/** The default \"pull one row into the offline DB\" primitive (§7). */\nexport function useOnDemandStream(\n name: string,\n params: Params | null,\n opts: OnDemandOptions = {},\n): OnDemandResult {\n const bridge = useBridge();\n const key = `${name}:${JSON.stringify(params)}:${JSON.stringify(opts)}`;\n return useRetained(bridge, key, () => bridge.onDemand(name, params, opts));\n}\n\n/** OPTIONAL: server-side flagging (§7). Prefer useOnDemandStream. */\nexport function useAutoSync(config: FlaggerConfig, ids: readonly string[]): FlagResult {\n const bridge = useBridge();\n const key = `${config.stream}:${JSON.stringify([...ids].sort())}`;\n return useRetained(bridge, key, () => bridge.autoSync(config, ids));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAQO;AACP,8BAAiC;AAqBjC,IAAM,oBAAgB,4BAA6B,IAAI;AACvD,IAAM,4BAAwB,4BAAc,IAAI;AAGzC,IAAM,iBAAiB,CAAC,EAAE,QAAQ,SAAS,MAAiD;AACjG,QAAM,mBAAe,yBAAW,qBAAqB;AACrD,aAAO,4BAAc,sBAAsB,UAAU,EAAE,OAAO,gBAAgB,OAAO,GAAG,QAAQ;AAClG;AAUO,SAAS,eAAe,EAAE,QAAQ,UAAU,OAAO,GAAwB;AAChF,8BAAU,MAAM;AACd,WAAO,UAAU,MAAM;AAAA,EACzB,GAAG,CAAC,QAAQ,MAAM,CAAC;AACnB,aAAO,4BAAc,cAAc,UAAU,EAAE,OAAO,OAAO,GAAG,QAAQ;AAC1E;AAWO,IAAM,mBAAmB,CAC9B,YAC8B;AAC9B,QAAM,SAAS,UAAU;AACzB,QAAM,aAAS,yBAAW,qBAAqB;AAC/C,QAAM,QAAQ,SAAS,MAAM;AAC7B,QAAM,UAAM,0CAAiB,OAAO;AAGpC,QAAM,iBAAa,sBAAQ,MAAM,OAAO,MAAM,OAAO,GAAG,CAAC,QAAQ,OAAO,GAAG,CAAC;AAC5E,8BAAU,MAAM;AACd,eAAW,OAAO,MAAM;AACxB,WAAO,MAAM,WAAW,QAAQ,MAAM;AAAA,EACxC,GAAG,CAAC,YAAY,MAAM,CAAC;AACvB,QAAM,aAAS;AAAA,IACb,WAAW,MAAM;AAAA,IACjB,WAAW,MAAM;AAAA,IACjB,WAAW,MAAM;AAAA,EACnB;AACA,aAAO;AAAA,IACL,OAAO;AAAA,MACL,GAAG;AAAA,MACH,eAAe,WAAW;AAAA,MAC1B,OAA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AAO,GAAG,CAAC;AAC7E,8BAAU,MAAM;AACd,UAAM,OAAO;AACb,WAAO,MAAM,MAAM,QAAQ;AAAA,EAC7B,GAAG,CAAC,KAAK,CAAC;AACV,QAAM,aAAS;AAAA,IACb,MAAM,MAAM;AAAA,IACZ,MAAM,MAAM;AAAA,IACZ,MAAM,MAAM;AAAA,EACd;AACA,aAAO;AAAA,IACL,OAAO,EAAE,GAAG,QAAQ,UAAU,MAAM,KAAK,MAAM,SAAS,GAAG,OAAO,MAAM,KAAK,MAAM,MAAM,EAAE;AAAA,IAC3F,CAAC,QAAQ,KAAK;AAAA,EAChB;AACF;AAGO,SAAS,kBACd,MACA,QACA,OAAwB,CAAC,GACT;AAChB,QAAM,SAAS,UAAU;AACzB,QAAM,MAAM,GAAG,IAAI,IAAI,KAAK,UAAU,MAAM,CAAC,IAAI,KAAK,UAAU,IAAI,CAAC;AACrE,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,SAAS,MAAM,QAAQ,IAAI,CAAC;AAC3E;AAGO,SAAS,YAAY,QAAuB,KAAoC;AACrF,QAAM,SAAS,UAAU;AACzB,QAAM,MAAM,GAAG,OAAO,MAAM,IAAI,KAAK,UAAU,CAAC,GAAG,GAAG,EAAE,KAAK,CAAC,CAAC;AAC/D,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,SAAS,QAAQ,GAAG,CAAC;AACpE;","names":[]}
package/dist/index.d.cts CHANGED
@@ -1,13 +1,31 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { Bridge, InfiniteListResult, FlaggerConfig, FlagResult, OrderKey, InfiniteListDefinition, Params, OnDemandOptions, OnDemandResult, RacedListDefinition, RacedListResult } from 'powersync-bridge';
3
+ import { Bridge, InfiniteListResult, InfiniteQueryResult, FlaggerConfig, FlagResult, OrderKey, InfiniteListDefinition, InfiniteQueryOptions, Params, OnDemandOptions, OnDemandResult, RacedListDefinition, RacedListResult } from 'powersync-bridge';
4
4
 
5
+ /** Pause read observers in a hidden subtree while retaining their scoped snapshots. */
6
+ declare const BridgeActivity: ({ active, children }: {
7
+ active: boolean;
8
+ children?: ReactNode;
9
+ }) => react.FunctionComponentElement<react.ProviderProps<boolean>>;
5
10
  interface BridgeProviderProps {
6
11
  bridge: Bridge;
7
12
  children?: ReactNode;
13
+ /** Native apps supply their network hook's result once, at the provider. */
14
+ online?: boolean | undefined;
8
15
  }
9
16
  /** Mount once at app root. Crud-delta observation started at createBridge(), not here (F6-001). */
10
- declare function BridgeProvider({ bridge, children }: BridgeProviderProps): react.FunctionComponentElement<react.ProviderProps<Bridge | null>>;
17
+ declare function BridgeProvider({ bridge, children, online }: BridgeProviderProps): react.FunctionComponentElement<react.ProviderProps<Bridge | null>>;
18
+ type UseInfiniteQueryResult<T> = InfiniteQueryResult<T> & {
19
+ fetchNextPage(): void;
20
+ retry(): void;
21
+ refresh(): void;
22
+ refetch(): void;
23
+ continueOlder(): void;
24
+ };
25
+ /** Define local SQL and an API page; the bridge owns all paging and reconciliation. */
26
+ declare const useInfiniteQuery: <T extends {
27
+ id: string;
28
+ }>(options: InfiniteQueryOptions<T>) => UseInfiniteQueryResult<T>;
11
29
  declare function useBridge(): Bridge;
12
30
  declare function useRacedList<TItem, TScope, TApi, K extends OrderKey<TItem>>(def: RacedListDefinition<TItem, TScope, TApi, K>, scope: TScope): RacedListResult<TItem>;
13
31
  interface UseInfiniteListResult<TItem> extends InfiniteListResult<TItem> {
@@ -21,4 +39,4 @@ declare function useOnDemandStream(name: string, params: Params | null, opts?: O
21
39
  /** OPTIONAL: server-side flagging (§7). Prefer useOnDemandStream. */
22
40
  declare function useAutoSync(config: FlaggerConfig, ids: readonly string[]): FlagResult;
23
41
 
24
- export { BridgeProvider, type BridgeProviderProps, type UseInfiniteListResult, useAutoSync, useBridge, useInfiniteList, useOnDemandStream, useRacedList };
42
+ export { BridgeActivity, BridgeProvider, type BridgeProviderProps, type UseInfiniteListResult, type UseInfiniteQueryResult, useAutoSync, useBridge, useInfiniteList, useInfiniteQuery, useOnDemandStream, useRacedList };
package/dist/index.d.ts CHANGED
@@ -1,13 +1,31 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { Bridge, InfiniteListResult, FlaggerConfig, FlagResult, OrderKey, InfiniteListDefinition, Params, OnDemandOptions, OnDemandResult, RacedListDefinition, RacedListResult } from 'powersync-bridge';
3
+ import { Bridge, InfiniteListResult, InfiniteQueryResult, FlaggerConfig, FlagResult, OrderKey, InfiniteListDefinition, InfiniteQueryOptions, Params, OnDemandOptions, OnDemandResult, RacedListDefinition, RacedListResult } from 'powersync-bridge';
4
4
 
5
+ /** Pause read observers in a hidden subtree while retaining their scoped snapshots. */
6
+ declare const BridgeActivity: ({ active, children }: {
7
+ active: boolean;
8
+ children?: ReactNode;
9
+ }) => react.FunctionComponentElement<react.ProviderProps<boolean>>;
5
10
  interface BridgeProviderProps {
6
11
  bridge: Bridge;
7
12
  children?: ReactNode;
13
+ /** Native apps supply their network hook's result once, at the provider. */
14
+ online?: boolean | undefined;
8
15
  }
9
16
  /** Mount once at app root. Crud-delta observation started at createBridge(), not here (F6-001). */
10
- declare function BridgeProvider({ bridge, children }: BridgeProviderProps): react.FunctionComponentElement<react.ProviderProps<Bridge | null>>;
17
+ declare function BridgeProvider({ bridge, children, online }: BridgeProviderProps): react.FunctionComponentElement<react.ProviderProps<Bridge | null>>;
18
+ type UseInfiniteQueryResult<T> = InfiniteQueryResult<T> & {
19
+ fetchNextPage(): void;
20
+ retry(): void;
21
+ refresh(): void;
22
+ refetch(): void;
23
+ continueOlder(): void;
24
+ };
25
+ /** Define local SQL and an API page; the bridge owns all paging and reconciliation. */
26
+ declare const useInfiniteQuery: <T extends {
27
+ id: string;
28
+ }>(options: InfiniteQueryOptions<T>) => UseInfiniteQueryResult<T>;
11
29
  declare function useBridge(): Bridge;
12
30
  declare function useRacedList<TItem, TScope, TApi, K extends OrderKey<TItem>>(def: RacedListDefinition<TItem, TScope, TApi, K>, scope: TScope): RacedListResult<TItem>;
13
31
  interface UseInfiniteListResult<TItem> extends InfiniteListResult<TItem> {
@@ -21,4 +39,4 @@ declare function useOnDemandStream(name: string, params: Params | null, opts?: O
21
39
  /** OPTIONAL: server-side flagging (§7). Prefer useOnDemandStream. */
22
40
  declare function useAutoSync(config: FlaggerConfig, ids: readonly string[]): FlagResult;
23
41
 
24
- export { BridgeProvider, type BridgeProviderProps, type UseInfiniteListResult, useAutoSync, useBridge, useInfiniteList, useOnDemandStream, useRacedList };
42
+ export { BridgeActivity, BridgeProvider, type BridgeProviderProps, type UseInfiniteListResult, type UseInfiniteQueryResult, useAutoSync, useBridge, useInfiniteList, useInfiniteQuery, useOnDemandStream, useRacedList };
package/dist/index.js CHANGED
@@ -1,30 +1,82 @@
1
1
  // src/index.ts
2
- import { createContext, createElement, useContext, useEffect, useMemo, useSyncExternalStore } from "react";
2
+ import {
3
+ createContext,
4
+ createElement,
5
+ useContext,
6
+ useEffect,
7
+ useMemo,
8
+ useSyncExternalStore
9
+ } from "react";
10
+ import { infiniteQueryKey } from "powersync-bridge";
3
11
  var BridgeContext = createContext(null);
4
- function BridgeProvider({ bridge, children }) {
12
+ var BridgeActivityContext = createContext(true);
13
+ var BridgeActivity = ({ active, children }) => {
14
+ const parentActive = useContext(BridgeActivityContext);
15
+ return createElement(BridgeActivityContext.Provider, { value: parentActive && active }, children);
16
+ };
17
+ function BridgeProvider({ bridge, children, online }) {
18
+ useEffect(() => {
19
+ bridge.setOnline(online);
20
+ }, [bridge, online]);
5
21
  return createElement(BridgeContext.Provider, { value: bridge }, children);
6
22
  }
23
+ var useInfiniteQuery = (options) => {
24
+ const bridge = useBridge();
25
+ const active = useContext(BridgeActivityContext);
26
+ const epoch = useEpoch(bridge);
27
+ const key = infiniteQueryKey(options);
28
+ const controller = useMemo(() => bridge.query(options), [bridge, epoch, key]);
29
+ useEffect(() => {
30
+ controller.retain(active);
31
+ return () => controller.release(active);
32
+ }, [controller, active]);
33
+ const result = useSyncExternalStore(
34
+ controller.store.subscribe,
35
+ controller.store.getSnapshot,
36
+ controller.store.getSnapshot
37
+ );
38
+ return useMemo(
39
+ () => ({
40
+ ...result,
41
+ fetchNextPage: controller.fetchNextPage,
42
+ retry: controller.retry,
43
+ refresh: controller.refresh,
44
+ refetch: controller.refresh,
45
+ continueOlder: controller.continueOlder
46
+ }),
47
+ [result, controller]
48
+ );
49
+ };
7
50
  function useBridge() {
8
51
  const b = useContext(BridgeContext);
9
52
  if (!b) throw new Error("powersync-bridge: no <BridgeProvider> above this component");
10
53
  return b;
11
54
  }
12
55
  function useEpoch(bridge) {
13
- return useSyncExternalStore(bridge.epochStore.subscribe, bridge.epochStore.getSnapshot, bridge.epochStore.getSnapshot);
56
+ return useSyncExternalStore(
57
+ bridge.epochStore.subscribe,
58
+ bridge.epochStore.getSnapshot,
59
+ bridge.epochStore.getSnapshot
60
+ );
14
61
  }
15
- function useRetained(bridge, key, acquire) {
62
+ function useRetained(bridge, key, acquire, active = true) {
16
63
  const epoch = useEpoch(bridge);
17
64
  const holder = useMemo(() => acquire(), [bridge, epoch, key]);
18
65
  useEffect(() => {
19
- holder.retain();
20
- return () => holder.release();
21
- }, [holder]);
22
- return useSyncExternalStore(holder.store.subscribe, holder.store.getSnapshot, holder.store.getSnapshot);
66
+ holder.retain(active);
67
+ return () => holder.release(active);
68
+ }, [holder, active]);
69
+ return useSyncExternalStore(
70
+ holder.store.subscribe,
71
+ holder.store.getSnapshot,
72
+ holder.store.getSnapshot
73
+ );
23
74
  }
24
75
  function useRacedList(def, scope) {
25
76
  const bridge = useBridge();
77
+ const active = useContext(BridgeActivityContext);
26
78
  const key = `${def.id}:${JSON.stringify(scope ?? null)}`;
27
- return useRetained(bridge, key, () => bridge.raced(def, scope));
79
+ return useRetained(bridge, key, () => bridge.raced(def, scope), active);
28
80
  }
29
81
  function useInfiniteList(def, scope) {
30
82
  const bridge = useBridge();
@@ -35,7 +87,11 @@ function useInfiniteList(def, scope) {
35
87
  store.retain();
36
88
  return () => store.release();
37
89
  }, [store]);
38
- const result = useSyncExternalStore(store.store.subscribe, store.store.getSnapshot, store.store.getSnapshot);
90
+ const result = useSyncExternalStore(
91
+ store.store.subscribe,
92
+ store.store.getSnapshot,
93
+ store.store.getSnapshot
94
+ );
39
95
  return useMemo(
40
96
  () => ({ ...result, loadMore: () => void store.loadMore(), retry: () => void store.retry() }),
41
97
  [result, store]
@@ -52,10 +108,12 @@ function useAutoSync(config, ids) {
52
108
  return useRetained(bridge, key, () => bridge.autoSync(config, ids));
53
109
  }
54
110
  export {
111
+ BridgeActivity,
55
112
  BridgeProvider,
56
113
  useAutoSync,
57
114
  useBridge,
58
115
  useInfiniteList,
116
+ useInfiniteQuery,
59
117
  useOnDemandStream,
60
118
  useRacedList
61
119
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createContext, createElement, useContext, useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react';\nimport type {\n Bridge,\n FlaggerConfig,\n FlagResult,\n InfiniteListDefinition,\n InfiniteListResult,\n OnDemandOptions,\n OnDemandResult,\n OrderKey,\n Params,\n RacedListDefinition,\n RacedListResult,\n Store,\n} from 'powersync-bridge';\n\n// NOTE (R11, static assertion): this package never imports `useQuery` from TanStack.\n// It renders from the engine store via useSyncExternalStore only.\n\nconst BridgeContext = createContext<Bridge | null>(null);\n\nexport interface BridgeProviderProps {\n bridge: Bridge;\n children?: ReactNode;\n}\n\n/** Mount once at app root. Crud-delta observation started at createBridge(), not here (F6-001). */\nexport function BridgeProvider({ bridge, children }: BridgeProviderProps) {\n return createElement(BridgeContext.Provider, { value: bridge }, children);\n}\n\nexport function useBridge(): Bridge {\n const b = useContext(BridgeContext);\n if (!b) throw new Error('powersync-bridge: no <BridgeProvider> above this component');\n return b;\n}\n\nfunction useEpoch(bridge: Bridge): number {\n return useSyncExternalStore(bridge.epochStore.subscribe, bridge.epochStore.getSnapshot, bridge.epochStore.getSnapshot);\n}\n\ninterface Retainable<S> {\n readonly store: Store<S>;\n retain(): void;\n release(): void;\n}\n\n/**\n * Acquire a ref-counted store for the current epoch and subscribe to it. Retain/release run in\n * an effect so StrictMode's double-invoke is a no-op pair (R10); the store is shared across\n * components that ask for the same definition + scope.\n */\nfunction useRetained<S>(bridge: Bridge, key: string, acquire: () => Retainable<S>): S {\n const epoch = useEpoch(bridge);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const holder = useMemo(() => acquire(), [bridge, epoch, key]);\n useEffect(() => {\n holder.retain();\n return () => holder.release();\n }, [holder]);\n return useSyncExternalStore(holder.store.subscribe, holder.store.getSnapshot, holder.store.getSnapshot);\n}\n\nexport function useRacedList<TItem, TScope, TApi, K extends OrderKey<TItem>>(\n def: RacedListDefinition<TItem, TScope, TApi, K>,\n scope: TScope,\n): RacedListResult<TItem> {\n const bridge = useBridge();\n const key = `${def.id}:${JSON.stringify(scope ?? null)}`;\n return useRetained(bridge, key, () => bridge.raced(def, scope));\n}\n\nexport interface UseInfiniteListResult<TItem> extends InfiniteListResult<TItem> {\n loadMore(): void;\n /** Clears API backoff and loads (R16). */\n retry(): void;\n}\n\nexport function useInfiniteList<TItem, TScope, K extends OrderKey<TItem>, TCursor, TPartition>(\n def: InfiniteListDefinition<TItem, TScope, K, TCursor, TPartition>,\n scope: TScope,\n): UseInfiniteListResult<TItem> {\n const bridge = useBridge();\n const epoch = useEpoch(bridge);\n const key = `${def.id}:${JSON.stringify(scope ?? null)}`;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const store = useMemo(() => bridge.infinite(def, scope), [bridge, epoch, key]);\n useEffect(() => {\n store.retain();\n return () => store.release();\n }, [store]);\n const result = useSyncExternalStore(store.store.subscribe, store.store.getSnapshot, store.store.getSnapshot);\n return useMemo(\n () => ({ ...result, loadMore: () => void store.loadMore(), retry: () => void store.retry() }),\n [result, store],\n );\n}\n\n/** The default \"pull one row into the offline DB\" primitive (§7). */\nexport function useOnDemandStream(name: string, params: Params | null, opts: OnDemandOptions = {}): OnDemandResult {\n const bridge = useBridge();\n const key = `${name}:${JSON.stringify(params)}:${JSON.stringify(opts)}`;\n return useRetained(bridge, key, () => bridge.onDemand(name, params, opts));\n}\n\n/** OPTIONAL: server-side flagging (§7). Prefer useOnDemandStream. */\nexport function useAutoSync(config: FlaggerConfig, ids: readonly string[]): FlagResult {\n const bridge = useBridge();\n const key = `${config.stream}:${JSON.stringify([...ids].sort())}`;\n return useRetained(bridge, key, () => bridge.autoSync(config, ids));\n}\n"],"mappings":";AAAA,SAAS,eAAe,eAAe,YAAY,WAAW,SAAS,4BAA4C;AAmBnH,IAAM,gBAAgB,cAA6B,IAAI;AAQhD,SAAS,eAAe,EAAE,QAAQ,SAAS,GAAwB;AACxE,SAAO,cAAc,cAAc,UAAU,EAAE,OAAO,OAAO,GAAG,QAAQ;AAC1E;AAEO,SAAS,YAAoB;AAClC,QAAM,IAAI,WAAW,aAAa;AAClC,MAAI,CAAC,EAAG,OAAM,IAAI,MAAM,4DAA4D;AACpF,SAAO;AACT;AAEA,SAAS,SAAS,QAAwB;AACxC,SAAO,qBAAqB,OAAO,WAAW,WAAW,OAAO,WAAW,aAAa,OAAO,WAAW,WAAW;AACvH;AAaA,SAAS,YAAe,QAAgB,KAAa,SAAiC;AACpF,QAAM,QAAQ,SAAS,MAAM;AAE7B,QAAM,SAAS,QAAQ,MAAM,QAAQ,GAAG,CAAC,QAAQ,OAAO,GAAG,CAAC;AAC5D,YAAU,MAAM;AACd,WAAO,OAAO;AACd,WAAO,MAAM,OAAO,QAAQ;AAAA,EAC9B,GAAG,CAAC,MAAM,CAAC;AACX,SAAO,qBAAqB,OAAO,MAAM,WAAW,OAAO,MAAM,aAAa,OAAO,MAAM,WAAW;AACxG;AAEO,SAAS,aACd,KACA,OACwB;AACxB,QAAM,SAAS,UAAU;AACzB,QAAM,MAAM,GAAG,IAAI,EAAE,IAAI,KAAK,UAAU,SAAS,IAAI,CAAC;AACtD,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,MAAM,KAAK,KAAK,CAAC;AAChE;AAQO,SAAS,gBACd,KACA,OAC8B;AAC9B,QAAM,SAAS,UAAU;AACzB,QAAM,QAAQ,SAAS,MAAM;AAC7B,QAAM,MAAM,GAAG,IAAI,EAAE,IAAI,KAAK,UAAU,SAAS,IAAI,CAAC;AAEtD,QAAM,QAAQ,QAAQ,MAAM,OAAO,SAAS,KAAK,KAAK,GAAG,CAAC,QAAQ,OAAO,GAAG,CAAC;AAC7E,YAAU,MAAM;AACd,UAAM,OAAO;AACb,WAAO,MAAM,MAAM,QAAQ;AAAA,EAC7B,GAAG,CAAC,KAAK,CAAC;AACV,QAAM,SAAS,qBAAqB,MAAM,MAAM,WAAW,MAAM,MAAM,aAAa,MAAM,MAAM,WAAW;AAC3G,SAAO;AAAA,IACL,OAAO,EAAE,GAAG,QAAQ,UAAU,MAAM,KAAK,MAAM,SAAS,GAAG,OAAO,MAAM,KAAK,MAAM,MAAM,EAAE;AAAA,IAC3F,CAAC,QAAQ,KAAK;AAAA,EAChB;AACF;AAGO,SAAS,kBAAkB,MAAc,QAAuB,OAAwB,CAAC,GAAmB;AACjH,QAAM,SAAS,UAAU;AACzB,QAAM,MAAM,GAAG,IAAI,IAAI,KAAK,UAAU,MAAM,CAAC,IAAI,KAAK,UAAU,IAAI,CAAC;AACrE,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,SAAS,MAAM,QAAQ,IAAI,CAAC;AAC3E;AAGO,SAAS,YAAY,QAAuB,KAAoC;AACrF,QAAM,SAAS,UAAU;AACzB,QAAM,MAAM,GAAG,OAAO,MAAM,IAAI,KAAK,UAAU,CAAC,GAAG,GAAG,EAAE,KAAK,CAAC,CAAC;AAC/D,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,SAAS,QAAQ,GAAG,CAAC;AACpE;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n createContext,\n createElement,\n useContext,\n useEffect,\n useMemo,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport { infiniteQueryKey } from 'powersync-bridge';\nimport type {\n Bridge,\n FlaggerConfig,\n FlagResult,\n InfiniteListDefinition,\n InfiniteListResult,\n InfiniteQueryOptions,\n InfiniteQueryResult,\n OnDemandOptions,\n OnDemandResult,\n OrderKey,\n Params,\n RacedListDefinition,\n RacedListResult,\n Store,\n} from 'powersync-bridge';\n\n// NOTE (R11, static assertion): this package never imports `useQuery` from TanStack.\n// It renders from the engine store via useSyncExternalStore only.\n\nconst BridgeContext = createContext<Bridge | null>(null);\nconst BridgeActivityContext = createContext(true);\n\n/** Pause read observers in a hidden subtree while retaining their scoped snapshots. */\nexport const BridgeActivity = ({ active, children }: { active: boolean; children?: ReactNode }) => {\n const parentActive = useContext(BridgeActivityContext);\n return createElement(BridgeActivityContext.Provider, { value: parentActive && active }, children);\n};\n\nexport interface BridgeProviderProps {\n bridge: Bridge;\n children?: ReactNode;\n /** Native apps supply their network hook's result once, at the provider. */\n online?: boolean | undefined;\n}\n\n/** Mount once at app root. Crud-delta observation started at createBridge(), not here (F6-001). */\nexport function BridgeProvider({ bridge, children, online }: BridgeProviderProps) {\n useEffect(() => {\n bridge.setOnline(online);\n }, [bridge, online]);\n return createElement(BridgeContext.Provider, { value: bridge }, children);\n}\n\nexport type UseInfiniteQueryResult<T> = InfiniteQueryResult<T> & {\n fetchNextPage(): void;\n retry(): void;\n refresh(): void;\n refetch(): void;\n continueOlder(): void;\n};\n\n/** Define local SQL and an API page; the bridge owns all paging and reconciliation. */\nexport const useInfiniteQuery = <T extends { id: string }>(\n options: InfiniteQueryOptions<T>,\n): UseInfiniteQueryResult<T> => {\n const bridge = useBridge();\n const active = useContext(BridgeActivityContext);\n const epoch = useEpoch(bridge);\n const key = infiniteQueryKey(options);\n // Definitions are closures; every changing predicate belongs in queryKey.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const controller = useMemo(() => bridge.query(options), [bridge, epoch, key]);\n useEffect(() => {\n controller.retain(active);\n return () => controller.release(active);\n }, [controller, active]);\n const result = useSyncExternalStore(\n controller.store.subscribe,\n controller.store.getSnapshot,\n controller.store.getSnapshot,\n );\n return useMemo(\n () => ({\n ...result,\n fetchNextPage: controller.fetchNextPage,\n retry: controller.retry,\n refresh: controller.refresh,\n refetch: controller.refresh,\n continueOlder: controller.continueOlder,\n }),\n [result, controller],\n );\n};\n\nexport function useBridge(): Bridge {\n const b = useContext(BridgeContext);\n if (!b) throw new Error('powersync-bridge: no <BridgeProvider> above this component');\n return b;\n}\n\nfunction useEpoch(bridge: Bridge): number {\n return useSyncExternalStore(\n bridge.epochStore.subscribe,\n bridge.epochStore.getSnapshot,\n bridge.epochStore.getSnapshot,\n );\n}\n\ninterface Retainable<S> {\n readonly store: Store<S>;\n retain(active?: boolean): void;\n release(active?: boolean): void;\n}\n\n/**\n * Acquire a ref-counted store for the current epoch and subscribe to it. Retain/release run in\n * an effect so StrictMode's double-invoke is a no-op pair (R10); the store is shared across\n * components that ask for the same definition + scope.\n */\nfunction useRetained<S>(\n bridge: Bridge,\n key: string,\n acquire: () => Retainable<S>,\n active = true,\n): S {\n const epoch = useEpoch(bridge);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const holder = useMemo(() => acquire(), [bridge, epoch, key]);\n useEffect(() => {\n holder.retain(active);\n return () => holder.release(active);\n }, [holder, active]);\n return useSyncExternalStore(\n holder.store.subscribe,\n holder.store.getSnapshot,\n holder.store.getSnapshot,\n );\n}\n\nexport function useRacedList<TItem, TScope, TApi, K extends OrderKey<TItem>>(\n def: RacedListDefinition<TItem, TScope, TApi, K>,\n scope: TScope,\n): RacedListResult<TItem> {\n const bridge = useBridge();\n const active = useContext(BridgeActivityContext);\n const key = `${def.id}:${JSON.stringify(scope ?? null)}`;\n return useRetained(bridge, key, () => bridge.raced(def, scope), active);\n}\n\nexport interface UseInfiniteListResult<TItem> extends InfiniteListResult<TItem> {\n loadMore(): void;\n /** Clears API backoff and loads (R16). */\n retry(): void;\n}\n\nexport function useInfiniteList<TItem, TScope, K extends OrderKey<TItem>, TCursor, TPartition>(\n def: InfiniteListDefinition<TItem, TScope, K, TCursor, TPartition>,\n scope: TScope,\n): UseInfiniteListResult<TItem> {\n const bridge = useBridge();\n const epoch = useEpoch(bridge);\n const key = `${def.id}:${JSON.stringify(scope ?? null)}`;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const store = useMemo(() => bridge.infinite(def, scope), [bridge, epoch, key]);\n useEffect(() => {\n store.retain();\n return () => store.release();\n }, [store]);\n const result = useSyncExternalStore(\n store.store.subscribe,\n store.store.getSnapshot,\n store.store.getSnapshot,\n );\n return useMemo(\n () => ({ ...result, loadMore: () => void store.loadMore(), retry: () => void store.retry() }),\n [result, store],\n );\n}\n\n/** The default \"pull one row into the offline DB\" primitive (§7). */\nexport function useOnDemandStream(\n name: string,\n params: Params | null,\n opts: OnDemandOptions = {},\n): OnDemandResult {\n const bridge = useBridge();\n const key = `${name}:${JSON.stringify(params)}:${JSON.stringify(opts)}`;\n return useRetained(bridge, key, () => bridge.onDemand(name, params, opts));\n}\n\n/** OPTIONAL: server-side flagging (§7). Prefer useOnDemandStream. */\nexport function useAutoSync(config: FlaggerConfig, ids: readonly string[]): FlagResult {\n const bridge = useBridge();\n const key = `${config.stream}:${JSON.stringify([...ids].sort())}`;\n return useRetained(bridge, key, () => bridge.autoSync(config, ids));\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,wBAAwB;AAqBjC,IAAM,gBAAgB,cAA6B,IAAI;AACvD,IAAM,wBAAwB,cAAc,IAAI;AAGzC,IAAM,iBAAiB,CAAC,EAAE,QAAQ,SAAS,MAAiD;AACjG,QAAM,eAAe,WAAW,qBAAqB;AACrD,SAAO,cAAc,sBAAsB,UAAU,EAAE,OAAO,gBAAgB,OAAO,GAAG,QAAQ;AAClG;AAUO,SAAS,eAAe,EAAE,QAAQ,UAAU,OAAO,G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AK,UAAU,IAAI,CAAC;AACrE,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,SAAS,MAAM,QAAQ,IAAI,CAAC;AAC3E;AAGO,SAAS,YAAY,QAAuB,KAAoC;AACrF,QAAM,SAAS,UAAU;AACzB,QAAM,MAAM,GAAG,OAAO,MAAM,IAAI,KAAK,UAAU,CAAC,GAAG,GAAG,EAAE,KAAK,CAAC,CAAC;AAC/D,SAAO,YAAY,QAAQ,KAAK,MAAM,OAAO,SAAS,QAAQ,GAAG,CAAC;AACpE;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync-bridge/react",
3
- "version": "0.0.1-alpha.0",
3
+ "version": "0.0.1-alpha.2",
4
4
  "description": "React bindings for powersync-bridge: BridgeProvider, useRacedList, useInfiniteList, useOnDemandStream, useAutoSync (useSyncExternalStore-based).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -41,14 +41,14 @@
41
41
  ],
42
42
  "peerDependencies": {
43
43
  "react": "^18.2.0 || ^19.0.0",
44
- "powersync-bridge": "0.0.1-alpha.0"
44
+ "powersync-bridge": "0.0.1-alpha.2"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/react": "^19.1.0",
48
48
  "react": "^19.1.0",
49
49
  "tsup": "^8.5.1",
50
50
  "typescript": "^5.9.0",
51
- "powersync-bridge": "0.0.1-alpha.0"
51
+ "powersync-bridge": "0.0.1-alpha.2"
52
52
  },
53
53
  "scripts": {
54
54
  "build": "tsup",