@powersync-bridge/react 0.0.1-alpha.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 akpor-kofi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,218 @@
1
+ # powersync-bridge
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.
22
+
23
+ ## What your backend must change
24
+
25
+ **Nothing.** No new tables, no new columns, no change to existing sync streams. The one rule is an
26
+ alignment, not a change: your list endpoint sorts rows the same way your local query does, with
27
+ `id` as the last tiebreaker.
28
+
29
+ | What you want | Streams you need | Routes you need |
30
+ |---|---|---|
31
+ | Fast, correct first paint of any list | none beyond what you have | your existing list endpoint |
32
+ | Scroll past the synced window, older pages from the API | none | the same endpoint accepting `cursor` (or `offset`, degraded) |
33
+ | Scroll past the synced window, older months into the offline DB | one stream with `subscription.parameter('month')`, partition computed with `substring()` on your existing timestamp | optional `GET …/floor` |
34
+ | Open one old record by id, offline-capable | one stream with `id = subscription.parameter('id')` | none |
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pnpm add powersync-bridge @powersync-bridge/react @powersync-bridge/drizzle @powersync-bridge/powersync
40
+ ```
41
+
42
+ Peers: `@powersync/common ^2.3`, `@powersync/web ^2.4` or `@powersync/react-native ^2.3`,
43
+ `@powersync/drizzle-driver`, `drizzle-orm`, `react ^18.2 || ^19`. TanStack Query is optional.
44
+
45
+ ## Setup (once, in a plain module)
46
+
47
+ ```ts
48
+ // bridge.ts
49
+ import { createBridge } from 'powersync-bridge';
50
+ import { createPowerSyncDriver } from '@powersync-bridge/powersync';
51
+ import { drizzleAdapter } from '@powersync-bridge/drizzle';
52
+ import { db, drizzle } from './db/powersync';
53
+
54
+ const adapter = drizzleAdapter(drizzle);
55
+ export const bridge = createBridge({
56
+ driver: createPowerSyncDriver(db, { adapter, onlineHint: () => navigator.onLine }),
57
+ adapter,
58
+ platformGates: { native: 'local-first', web: 'race' },
59
+ });
60
+ ```
61
+
62
+ ```ts
63
+ // db/boot.ts — connect THROUGH the bridge: identity is derived from the JWT your connector
64
+ // already returns. Never pass claims yourself.
65
+ await db.init();
66
+ await db.connect(bridge.wrapConnector(connector));
67
+ ```
68
+
69
+ ```tsx
70
+ // App.tsx
71
+ <BridgeProvider bridge={bridge}>
72
+ <Router />
73
+ </BridgeProvider>
74
+ ```
75
+
76
+ ## A raced list (page 1, with joins)
77
+
78
+ ```ts
79
+ import { z } from 'zod';
80
+ import { desc, eq } from 'drizzle-orm';
81
+ import { defineRacedList } from 'powersync-bridge';
82
+ import { drizzle } from '../db/powersync';
83
+ import { sales, customers, users } from '../db/schema';
84
+
85
+ const SaleApi = z.object({
86
+ id: z.string(), sold_at: z.string(), total: z.string(),
87
+ status: z.enum(['OPEN', 'PAID', 'VOID']), item_count: z.number().int(),
88
+ customer_name: z.string(), seller_name: z.string(),
89
+ });
90
+ type SaleApi = z.infer<typeof SaleApi>;
91
+
92
+ export const RecentSales = defineRacedList({
93
+ id: 'recent-sales',
94
+ table: 'sales',
95
+ // The row type is inferred from this query. Annotate the scope; close over your drizzle instance.
96
+ query: ({ orgId }: { orgId: string }) =>
97
+ drizzle
98
+ .select({
99
+ id: sales.id, soldAt: sales.soldAt, total: sales.total, status: sales.status,
100
+ itemCount: sales.itemCount, customerName: customers.name, sellerName: users.displayName,
101
+ })
102
+ .from(sales)
103
+ .innerJoin(customers, eq(customers.id, sales.customerId))
104
+ .innerJoin(users, eq(users.id, sales.sellerId))
105
+ .where(eq(sales.orgId, orgId))
106
+ .orderBy(desc(sales.soldAt), desc(sales.id))
107
+ .limit(50),
108
+ fetchSnapshot: async (_scope, signal) => {
109
+ const res = await api.get('/api/sales?limit=50', { signal });
110
+ return { rows: z.array(SaleApi).parse(res.items) };
111
+ },
112
+ mapApi: (o: SaleApi) => ({ // return type is checked against the query's row type
113
+ id: o.id, soldAt: o.sold_at, total: o.total, status: o.status,
114
+ itemCount: o.item_count, customerName: o.customer_name, sellerName: o.seller_name,
115
+ }),
116
+ orderKey: ['soldAt', 'id'] as const, // `id` is always the implicit tiebreaker
117
+ direction: 'desc',
118
+ limit: 50,
119
+ stream: { name: 'sales_window', params: null },
120
+ });
121
+ ```
122
+
123
+ ```tsx
124
+ function RecentSalesScreen({ orgId }: { orgId: string }) {
125
+ const { items, state, errors } = useRacedList(RecentSales, { orgId });
126
+ if (state === 'pending') return <Skeleton />;
127
+ return (
128
+ <FlatList
129
+ data={items}
130
+ keyExtractor={(r) => r.row.id}
131
+ renderItem={({ item }) => (
132
+ <SaleRow
133
+ sale={item.row}
134
+ muted={item.stale === true || !item.presentLocally}
135
+ onVoid={item.presentLocally ? () => voidSale(item.row.id) : undefined} // presence-gated writes
136
+ />
137
+ )}
138
+ />
139
+ );
140
+ }
141
+ ```
142
+
143
+ ## An infinite list (older months via sync streams)
144
+
145
+ ```ts
146
+ import { defineInfiniteList, type Cursor, type PageArgs } from 'powersync-bridge';
147
+
148
+ type SaleCursor = Cursor<SaleRow, ['soldAt', 'id']>; // [string, string] | undefined
149
+
150
+ export const SalesHistory = defineInfiniteList({
151
+ id: 'sales-history',
152
+ table: 'sales',
153
+ pageSize: 50,
154
+ orderKey: ['soldAt', 'id'] as const,
155
+ direction: 'desc',
156
+ // Annotate the page argument with the Cursor type; the row type is inferred from the return.
157
+ query: ({ cursor, limit }: PageArgs<SaleCursor>, { orgId }: { orgId: string }) =>
158
+ drizzle.select(projection).from(sales) /* …joins… */
159
+ .where(and(eq(sales.orgId, orgId), cursor ? or(lt(sales.soldAt, cursor[0]), and(eq(sales.soldAt, cursor[0]), lt(sales.id, cursor[1]))) : undefined))
160
+ .orderBy(desc(sales.soldAt), desc(sales.id))
161
+ .limit(limit),
162
+ escalate: {
163
+ kind: 'partition',
164
+ stream: 'sales_month',
165
+ partitionOf: (c) => (c ? c[0].slice(0, 7) : currentMonth()),
166
+ nextPartition: prevMonth,
167
+ partitionParams: (m) => ({ month: m }),
168
+ floor: '2015-01', // static floor, always required
169
+ serverFloor: async () => (await api.get('/api/sales/floor')).month, // optional exact floor
170
+ },
171
+ });
172
+ ```
173
+
174
+ ```yaml
175
+ # sync_streams.yaml — no partition column; the month is computed from your existing timestamp
176
+ sales_month:
177
+ query: >
178
+ SELECT * FROM sales
179
+ WHERE org_id = auth.parameter('org_id')
180
+ AND substring(sold_at::text, 1, 7) = subscription.parameter('month')
181
+ ```
182
+
183
+ Or escalate through your API instead (`kind: 'api'` with a cursor, or `kind: 'api-offset'` for
184
+ offset-only APIs, where duplicates are dropped and a shift is reported in `warnings`).
185
+
186
+ ## Rules that make it safe
187
+
188
+ - **Pending writes always win** — the live upload queue, a seeded snapshot-lifetime window, and
189
+ recently-acked writes shield your edits from an older API snapshot.
190
+ - **Freshness is session-scoped** — PowerSync's persisted `hasSynced` never counts as "fresh";
191
+ a checkpoint is stamped at its download start and the stamp is monotonic.
192
+ - **Deletes never resurrect** — a pending delete tombstones its id for the snapshot's lifetime.
193
+ - **Removals are classified** — a batched presence probe distinguishes filtered-out from
194
+ deleted; stream expiry distinguishes deleted from evicted; evicted rows stay visible but
195
+ are marked `presentLocally: false` and cannot be written.
196
+ - **Identity is derived** — from the connector's JWT, deny-listing volatile claims; an org
197
+ switch swaps every store's root synchronously, so no frame renders the outgoing tenant.
198
+
199
+ Sorting constraints: the sort column must compare identically on Postgres and SQLite.
200
+ ISO-8601 UTC strings, integers and uuidv7 are safe. For text use `ORDER BY col COLLATE "C"` on
201
+ the API; for decimals declare the column as `column.real` in the client schema.
202
+
203
+ ## Testing your own lists
204
+
205
+ `powersync-bridge/testing` ships a `FakeDriver` with virtual time: script sync status,
206
+ checkpoints, uploads, stream first-syncs and API responses, then assert on interleavings. See
207
+ `packages/core/test` for the invariant suite (T1–T44 in ARCHITECTURE.md §12.2).
208
+
209
+ ## Layout
210
+
211
+ ```
212
+ packages/core powersync-bridge engine, definitions, testing driver
213
+ packages/react @powersync-bridge/react BridgeProvider + hooks
214
+ packages/adapters/drizzle @powersync-bridge/drizzle builder → PreparedQuery (decoded rows)
215
+ packages/powersync @powersync-bridge/powersync BridgeDriver over @powersync/common
216
+ ```
217
+
218
+ Design: `ARCHITECTURE.md`. Build brief and worked example: `BUILD-READINESS.md`.
package/dist/index.cjs ADDED
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ BridgeProvider: () => BridgeProvider,
24
+ useAutoSync: () => useAutoSync,
25
+ useBridge: () => useBridge,
26
+ useInfiniteList: () => useInfiniteList,
27
+ useOnDemandStream: () => useOnDemandStream,
28
+ useRacedList: () => useRacedList
29
+ });
30
+ module.exports = __toCommonJS(src_exports);
31
+ var import_react = require("react");
32
+ var BridgeContext = (0, import_react.createContext)(null);
33
+ function BridgeProvider({ bridge, children }) {
34
+ return (0, import_react.createElement)(BridgeContext.Provider, { value: bridge }, children);
35
+ }
36
+ function useBridge() {
37
+ const b = (0, import_react.useContext)(BridgeContext);
38
+ if (!b) throw new Error("powersync-bridge: no <BridgeProvider> above this component");
39
+ return b;
40
+ }
41
+ function useEpoch(bridge) {
42
+ return (0, import_react.useSyncExternalStore)(bridge.epochStore.subscribe, bridge.epochStore.getSnapshot, bridge.epochStore.getSnapshot);
43
+ }
44
+ function useRetained(bridge, key, acquire) {
45
+ const epoch = useEpoch(bridge);
46
+ const holder = (0, import_react.useMemo)(() => acquire(), [bridge, epoch, key]);
47
+ (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);
52
+ }
53
+ function useRacedList(def, scope) {
54
+ const bridge = useBridge();
55
+ const key = `${def.id}:${JSON.stringify(scope ?? null)}`;
56
+ return useRetained(bridge, key, () => bridge.raced(def, scope));
57
+ }
58
+ function useInfiniteList(def, scope) {
59
+ const bridge = useBridge();
60
+ const epoch = useEpoch(bridge);
61
+ const key = `${def.id}:${JSON.stringify(scope ?? null)}`;
62
+ const store = (0, import_react.useMemo)(() => bridge.infinite(def, scope), [bridge, epoch, key]);
63
+ (0, import_react.useEffect)(() => {
64
+ store.retain();
65
+ return () => store.release();
66
+ }, [store]);
67
+ const result = (0, import_react.useSyncExternalStore)(store.store.subscribe, store.store.getSnapshot, store.store.getSnapshot);
68
+ return (0, import_react.useMemo)(
69
+ () => ({ ...result, loadMore: () => void store.loadMore(), retry: () => void store.retry() }),
70
+ [result, store]
71
+ );
72
+ }
73
+ function useOnDemandStream(name, params, opts = {}) {
74
+ const bridge = useBridge();
75
+ const key = `${name}:${JSON.stringify(params)}:${JSON.stringify(opts)}`;
76
+ return useRetained(bridge, key, () => bridge.onDemand(name, params, opts));
77
+ }
78
+ function useAutoSync(config, ids) {
79
+ const bridge = useBridge();
80
+ const key = `${config.stream}:${JSON.stringify([...ids].sort())}`;
81
+ return useRetained(bridge, key, () => bridge.autoSync(config, ids));
82
+ }
83
+ // Annotate the CommonJS export names for ESM import in node:
84
+ 0 && (module.exports = {
85
+ BridgeProvider,
86
+ useAutoSync,
87
+ useBridge,
88
+ useInfiniteList,
89
+ useOnDemandStream,
90
+ useRacedList
91
+ });
92
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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;AAA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M,OAAO;AACb,WAAO,MAAM,MAAM,QAAQ;AAAA,EAC7B,GAAG,CAAC,KAAK,CAAC;AACV,QAAM,aAAS,mCAAqB,MAAM,MAAM,WAAW,MAAM,MAAM,aAAa,MAAM,MAAM,WAAW;AAC3G,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,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":[]}
@@ -0,0 +1,24 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { Bridge, InfiniteListResult, FlaggerConfig, FlagResult, OrderKey, InfiniteListDefinition, Params, OnDemandOptions, OnDemandResult, RacedListDefinition, RacedListResult } from 'powersync-bridge';
4
+
5
+ interface BridgeProviderProps {
6
+ bridge: Bridge;
7
+ children?: ReactNode;
8
+ }
9
+ /** 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>>;
11
+ declare function useBridge(): Bridge;
12
+ declare function useRacedList<TItem, TScope, TApi, K extends OrderKey<TItem>>(def: RacedListDefinition<TItem, TScope, TApi, K>, scope: TScope): RacedListResult<TItem>;
13
+ interface UseInfiniteListResult<TItem> extends InfiniteListResult<TItem> {
14
+ loadMore(): void;
15
+ /** Clears API backoff and loads (R16). */
16
+ retry(): void;
17
+ }
18
+ declare function useInfiniteList<TItem, TScope, K extends OrderKey<TItem>, TCursor, TPartition>(def: InfiniteListDefinition<TItem, TScope, K, TCursor, TPartition>, scope: TScope): UseInfiniteListResult<TItem>;
19
+ /** The default "pull one row into the offline DB" primitive (§7). */
20
+ declare function useOnDemandStream(name: string, params: Params | null, opts?: OnDemandOptions): OnDemandResult;
21
+ /** OPTIONAL: server-side flagging (§7). Prefer useOnDemandStream. */
22
+ declare function useAutoSync(config: FlaggerConfig, ids: readonly string[]): FlagResult;
23
+
24
+ export { BridgeProvider, type BridgeProviderProps, type UseInfiniteListResult, useAutoSync, useBridge, useInfiniteList, useOnDemandStream, useRacedList };
@@ -0,0 +1,24 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { Bridge, InfiniteListResult, FlaggerConfig, FlagResult, OrderKey, InfiniteListDefinition, Params, OnDemandOptions, OnDemandResult, RacedListDefinition, RacedListResult } from 'powersync-bridge';
4
+
5
+ interface BridgeProviderProps {
6
+ bridge: Bridge;
7
+ children?: ReactNode;
8
+ }
9
+ /** 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>>;
11
+ declare function useBridge(): Bridge;
12
+ declare function useRacedList<TItem, TScope, TApi, K extends OrderKey<TItem>>(def: RacedListDefinition<TItem, TScope, TApi, K>, scope: TScope): RacedListResult<TItem>;
13
+ interface UseInfiniteListResult<TItem> extends InfiniteListResult<TItem> {
14
+ loadMore(): void;
15
+ /** Clears API backoff and loads (R16). */
16
+ retry(): void;
17
+ }
18
+ declare function useInfiniteList<TItem, TScope, K extends OrderKey<TItem>, TCursor, TPartition>(def: InfiniteListDefinition<TItem, TScope, K, TCursor, TPartition>, scope: TScope): UseInfiniteListResult<TItem>;
19
+ /** The default "pull one row into the offline DB" primitive (§7). */
20
+ declare function useOnDemandStream(name: string, params: Params | null, opts?: OnDemandOptions): OnDemandResult;
21
+ /** OPTIONAL: server-side flagging (§7). Prefer useOnDemandStream. */
22
+ declare function useAutoSync(config: FlaggerConfig, ids: readonly string[]): FlagResult;
23
+
24
+ export { BridgeProvider, type BridgeProviderProps, type UseInfiniteListResult, useAutoSync, useBridge, useInfiniteList, useOnDemandStream, useRacedList };
package/dist/index.js ADDED
@@ -0,0 +1,62 @@
1
+ // src/index.ts
2
+ import { createContext, createElement, useContext, useEffect, useMemo, useSyncExternalStore } from "react";
3
+ var BridgeContext = createContext(null);
4
+ function BridgeProvider({ bridge, children }) {
5
+ return createElement(BridgeContext.Provider, { value: bridge }, children);
6
+ }
7
+ function useBridge() {
8
+ const b = useContext(BridgeContext);
9
+ if (!b) throw new Error("powersync-bridge: no <BridgeProvider> above this component");
10
+ return b;
11
+ }
12
+ function useEpoch(bridge) {
13
+ return useSyncExternalStore(bridge.epochStore.subscribe, bridge.epochStore.getSnapshot, bridge.epochStore.getSnapshot);
14
+ }
15
+ function useRetained(bridge, key, acquire) {
16
+ const epoch = useEpoch(bridge);
17
+ const holder = useMemo(() => acquire(), [bridge, epoch, key]);
18
+ useEffect(() => {
19
+ holder.retain();
20
+ return () => holder.release();
21
+ }, [holder]);
22
+ return useSyncExternalStore(holder.store.subscribe, holder.store.getSnapshot, holder.store.getSnapshot);
23
+ }
24
+ function useRacedList(def, scope) {
25
+ const bridge = useBridge();
26
+ const key = `${def.id}:${JSON.stringify(scope ?? null)}`;
27
+ return useRetained(bridge, key, () => bridge.raced(def, scope));
28
+ }
29
+ function useInfiniteList(def, scope) {
30
+ const bridge = useBridge();
31
+ const epoch = useEpoch(bridge);
32
+ const key = `${def.id}:${JSON.stringify(scope ?? null)}`;
33
+ const store = useMemo(() => bridge.infinite(def, scope), [bridge, epoch, key]);
34
+ useEffect(() => {
35
+ store.retain();
36
+ return () => store.release();
37
+ }, [store]);
38
+ const result = useSyncExternalStore(store.store.subscribe, store.store.getSnapshot, store.store.getSnapshot);
39
+ return useMemo(
40
+ () => ({ ...result, loadMore: () => void store.loadMore(), retry: () => void store.retry() }),
41
+ [result, store]
42
+ );
43
+ }
44
+ function useOnDemandStream(name, params, opts = {}) {
45
+ const bridge = useBridge();
46
+ const key = `${name}:${JSON.stringify(params)}:${JSON.stringify(opts)}`;
47
+ return useRetained(bridge, key, () => bridge.onDemand(name, params, opts));
48
+ }
49
+ function useAutoSync(config, ids) {
50
+ const bridge = useBridge();
51
+ const key = `${config.stream}:${JSON.stringify([...ids].sort())}`;
52
+ return useRetained(bridge, key, () => bridge.autoSync(config, ids));
53
+ }
54
+ export {
55
+ BridgeProvider,
56
+ useAutoSync,
57
+ useBridge,
58
+ useInfiniteList,
59
+ useOnDemandStream,
60
+ useRacedList
61
+ };
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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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AY,QAAQ,KAAK,MAAM,OAAO,SAAS,QAAQ,GAAG,CAAC;AACpE;","names":[]}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@powersync-bridge/react",
3
+ "version": "0.0.1-alpha.0",
4
+ "description": "React bindings for powersync-bridge: BridgeProvider, useRacedList, useInfiniteList, useOnDemandStream, useAutoSync (useSyncExternalStore-based).",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/akpor-kofi/powersync-bridge.git",
11
+ "directory": "packages/react"
12
+ },
13
+ "homepage": "https://github.com/akpor-kofi/powersync-bridge#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/akpor-kofi/powersync-bridge/issues"
16
+ },
17
+ "keywords": [
18
+ "powersync",
19
+ "offline-first",
20
+ "local-first",
21
+ "sqlite",
22
+ "sync",
23
+ "react",
24
+ "hooks"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "main": "./dist/index.cjs",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js",
36
+ "require": "./dist/index.cjs"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist"
41
+ ],
42
+ "peerDependencies": {
43
+ "react": "^18.2.0 || ^19.0.0",
44
+ "powersync-bridge": "0.0.1-alpha.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/react": "^19.1.0",
48
+ "react": "^19.1.0",
49
+ "tsup": "^8.5.1",
50
+ "typescript": "^5.9.0",
51
+ "powersync-bridge": "0.0.1-alpha.0"
52
+ },
53
+ "scripts": {
54
+ "build": "tsup",
55
+ "typecheck": "tsc --noEmit"
56
+ }
57
+ }