@roko-app/instant-react-common 0.0.0-stage → 1.0.67-roko.1

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 (77) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +16 -0
  3. package/.tshy/esm.json +15 -0
  4. package/LICENSE +202 -0
  5. package/README.md +59 -2
  6. package/dist/commonjs/InstantReactAbstractDatabase.d.ts +283 -0
  7. package/dist/commonjs/InstantReactAbstractDatabase.d.ts.map +1 -0
  8. package/dist/commonjs/InstantReactAbstractDatabase.js +390 -0
  9. package/dist/commonjs/InstantReactAbstractDatabase.js.map +1 -0
  10. package/dist/commonjs/InstantReactRoom.d.ts +183 -0
  11. package/dist/commonjs/InstantReactRoom.d.ts.map +1 -0
  12. package/dist/commonjs/InstantReactRoom.js +290 -0
  13. package/dist/commonjs/InstantReactRoom.js.map +1 -0
  14. package/dist/commonjs/index.d.ts +5 -0
  15. package/dist/commonjs/index.d.ts.map +1 -0
  16. package/dist/commonjs/index.js +11 -0
  17. package/dist/commonjs/index.js.map +1 -0
  18. package/dist/commonjs/package.json +3 -0
  19. package/dist/commonjs/useInfiniteQuerySubscription.d.ts +28 -0
  20. package/dist/commonjs/useInfiniteQuerySubscription.d.ts.map +1 -0
  21. package/dist/commonjs/useInfiniteQuerySubscription.js +57 -0
  22. package/dist/commonjs/useInfiniteQuerySubscription.js.map +1 -0
  23. package/dist/commonjs/useQuery.d.ts +7 -0
  24. package/dist/commonjs/useQuery.d.ts.map +1 -0
  25. package/dist/commonjs/useQuery.js +79 -0
  26. package/dist/commonjs/useQuery.js.map +1 -0
  27. package/dist/commonjs/useTimeout.d.ts +5 -0
  28. package/dist/commonjs/useTimeout.d.ts.map +1 -0
  29. package/dist/commonjs/useTimeout.js +21 -0
  30. package/dist/commonjs/useTimeout.js.map +1 -0
  31. package/dist/commonjs/version.d.ts +3 -0
  32. package/dist/commonjs/version.d.ts.map +1 -0
  33. package/dist/commonjs/version.js +5 -0
  34. package/dist/commonjs/version.js.map +1 -0
  35. package/dist/esm/InstantReactAbstractDatabase.d.ts +283 -0
  36. package/dist/esm/InstantReactAbstractDatabase.d.ts.map +1 -0
  37. package/dist/esm/InstantReactAbstractDatabase.js +387 -0
  38. package/dist/esm/InstantReactAbstractDatabase.js.map +1 -0
  39. package/dist/esm/InstantReactRoom.d.ts +183 -0
  40. package/dist/esm/InstantReactRoom.d.ts.map +1 -0
  41. package/dist/esm/InstantReactRoom.js +281 -0
  42. package/dist/esm/InstantReactRoom.js.map +1 -0
  43. package/dist/esm/index.d.ts +5 -0
  44. package/dist/esm/index.d.ts.map +1 -0
  45. package/dist/esm/index.js +4 -0
  46. package/dist/esm/index.js.map +1 -0
  47. package/dist/esm/package.json +3 -0
  48. package/dist/esm/useInfiniteQuerySubscription.d.ts +28 -0
  49. package/dist/esm/useInfiniteQuerySubscription.d.ts.map +1 -0
  50. package/dist/esm/useInfiniteQuerySubscription.js +54 -0
  51. package/dist/esm/useInfiniteQuerySubscription.js.map +1 -0
  52. package/dist/esm/useQuery.d.ts +7 -0
  53. package/dist/esm/useQuery.d.ts.map +1 -0
  54. package/dist/esm/useQuery.js +76 -0
  55. package/dist/esm/useQuery.js.map +1 -0
  56. package/dist/esm/useTimeout.d.ts +5 -0
  57. package/dist/esm/useTimeout.d.ts.map +1 -0
  58. package/dist/esm/useTimeout.js +18 -0
  59. package/dist/esm/useTimeout.js.map +1 -0
  60. package/dist/esm/version.d.ts +3 -0
  61. package/dist/esm/version.d.ts.map +1 -0
  62. package/dist/esm/version.js +3 -0
  63. package/dist/esm/version.js.map +1 -0
  64. package/dist/standalone/index.js +8718 -0
  65. package/dist/standalone/index.umd.cjs +36 -0
  66. package/package.json +43 -3
  67. package/src/InstantReactAbstractDatabase.tsx +510 -0
  68. package/src/InstantReactRoom.ts +451 -0
  69. package/src/index.ts +9 -0
  70. package/src/useInfiniteQuerySubscription.ts +128 -0
  71. package/src/useQuery.ts +124 -0
  72. package/src/useTimeout.ts +22 -0
  73. package/src/version.ts +3 -0
  74. package/tsconfig.cjs.dev.json +15 -0
  75. package/tsconfig.dev.json +14 -0
  76. package/tsconfig.json +12 -0
  77. package/vite.config.ts +35 -0
@@ -0,0 +1,283 @@
1
+ import { Auth, Storage, type AuthState, type User, type ConnectionStatus, type AppStatusState, type TransactionChunk, type RoomSchemaShape, type InstaQLOptions, type InstantConfig, type PageInfoResponse, InstantCoreDatabase, InstaQLLifecycleState, InstaQLResponse, RoomsOf, InstantSchemaDef, IInstantDatabase, ValidQuery, Streams } from '@instantdb/core';
2
+ import { ReactNode } from 'react';
3
+ import { type InfiniteQueryResult } from './useInfiniteQuerySubscription.ts';
4
+ import { InstantReactRoom } from './InstantReactRoom.ts';
5
+ export default abstract class InstantReactAbstractDatabase<Schema extends InstantSchemaDef<any, any, any>, UseDates extends boolean = false, Config extends InstantConfig<Schema, boolean> = InstantConfig<Schema, UseDates>, Rooms extends RoomSchemaShape = RoomsOf<Schema>> implements IInstantDatabase<Schema> {
6
+ tx: import("@instantdb/core").TxChunk<Schema>;
7
+ auth: Auth;
8
+ storage: Storage;
9
+ streams: Streams;
10
+ core: InstantCoreDatabase<Schema, UseDates>;
11
+ /** @deprecated use `core` instead */
12
+ _core: InstantCoreDatabase<Schema, UseDates>;
13
+ static Store?: any;
14
+ static NetworkListener?: any;
15
+ static EventSourceImpl?: any;
16
+ constructor(config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {
17
+ useDateObjects?: UseDates;
18
+ }, versions?: {
19
+ [key: string]: string;
20
+ });
21
+ /**
22
+ * Returns a unique ID for a given `name`. It's stored in local storage,
23
+ * so you will get the same ID across sessions.
24
+ *
25
+ * This is useful for generating IDs that could identify a local device or user.
26
+ *
27
+ * @example
28
+ * const deviceId = await db.getLocalId('device');
29
+ */
30
+ getLocalId: (name: string) => Promise<string>;
31
+ /**
32
+ * A hook that returns a unique ID for a given `name`. localIds are
33
+ * stored in local storage, so you will get the same ID across sessions.
34
+ *
35
+ * Initially returns `null`, and then loads the localId.
36
+ *
37
+ * @example
38
+ * const deviceId = db.useLocalId('device');
39
+ * if (!deviceId) return null; // loading
40
+ * console.log('Device ID:', deviceId)
41
+ */
42
+ useLocalId: (name: string) => string | null;
43
+ /**
44
+ * Obtain a handle to a room, which allows you to listen to topics and presence data
45
+ *
46
+ * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`
47
+ * as the room type and id, respectively.
48
+ *
49
+ * @see https://instantdb.com/docs/presence-and-topics
50
+ *
51
+ * @example
52
+ * const room = db.room('chat', roomId);
53
+ * const { peers } = db.rooms.usePresence(room);
54
+ */
55
+ room<RoomType extends string & keyof Rooms>(type?: RoomType, id?: string): InstantReactRoom<Schema, Rooms, RoomType>;
56
+ /**
57
+ * Hooks for working with rooms
58
+ *
59
+ * @see https://instantdb.com/docs/presence-and-topics
60
+ *
61
+ * @example
62
+ * const room = db.room('chat', roomId);
63
+ * const { peers } = db.rooms.usePresence(room);
64
+ * const publish = db.rooms.usePublishTopic(room, 'emoji');
65
+ * // ...
66
+ */
67
+ rooms: {
68
+ useTopicEffect: typeof import("./InstantReactRoom.ts").useTopicEffect;
69
+ usePublishTopic: typeof import("./InstantReactRoom.ts").usePublishTopic;
70
+ usePresence: typeof import("./InstantReactRoom.ts").usePresence;
71
+ useSyncPresence: typeof import("./InstantReactRoom.ts").useSyncPresence;
72
+ useTypingIndicator: typeof import("./InstantReactRoom.ts").useTypingIndicator;
73
+ };
74
+ /**
75
+ * Use this to write data! You can create, update, delete, and link objects
76
+ *
77
+ * @see https://instantdb.com/docs/instaml
78
+ *
79
+ * @example
80
+ * // Create a new object in the `goals` namespace
81
+ * const goalId = id();
82
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
83
+ *
84
+ * // Update the title
85
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
86
+ *
87
+ * // Delete it
88
+ * db.transact(db.tx.goals[goalId].delete())
89
+ *
90
+ * // Or create an association:
91
+ * todoId = id();
92
+ * db.transact([
93
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
94
+ * db.tx.goals[goalId].link({todos: todoId}),
95
+ * ])
96
+ */
97
+ transact: (chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[]) => Promise<import("@instantdb/core").TransactionResult>;
98
+ /**
99
+ * Use this to query your data!
100
+ *
101
+ * @see https://instantdb.com/docs/instaql
102
+ *
103
+ * @example
104
+ * // listen to all goals
105
+ * const { isLoading, error, data } = db.useQuery({ goals: {} });
106
+ *
107
+ * // goals where the title is "Get Fit"
108
+ * const { isLoading, error, data } = db.useQuery({
109
+ * goals: { $: { where: { title: 'Get Fit' } } },
110
+ * });
111
+ *
112
+ * // all goals, _alongside_ their todos
113
+ * const { isLoading, error, data } = db.useQuery({
114
+ * goals: { todos: {} },
115
+ * });
116
+ *
117
+ * // skip if `user` is not logged in
118
+ * const { isLoading, error, data } = db.useQuery(
119
+ * auth.user ? { goals: {} } : null,
120
+ * );
121
+ */
122
+ useQuery: <Q extends ValidQuery<Q, Schema>>(query: null | Q, opts?: InstaQLOptions) => InstaQLLifecycleState<Schema, Q, UseDates>;
123
+ /**
124
+ * Listen for the logged in state. This is useful
125
+ * for deciding when to show a login screen.
126
+ *
127
+ * Check out the docs for an example `Login` component too!
128
+ *
129
+ * @see https://instantdb.com/docs/auth
130
+ * @example
131
+ * function App() {
132
+ * const { isLoading, user, error } = db.useAuth()
133
+ * if (isLoading) {
134
+ * return <div>Loading...</div>
135
+ * }
136
+ * if (error) {
137
+ * return <div>Uh oh! {error.message}</div>
138
+ * }
139
+ * if (user) {
140
+ * return <Main user={user} />
141
+ * }
142
+ * return <Login />
143
+ * }
144
+ *
145
+ */
146
+ useAuth: () => AuthState;
147
+ protected _useAuth(): AuthState;
148
+ /**
149
+ * Subscribe to the currently logged in user.
150
+ * If the user is not logged in, this hook with throw an Error.
151
+ * You will want to protect any calls of this hook with a
152
+ * <db.SignedIn> component, or your own logic based on db.useAuth()
153
+ *
154
+ * @see https://instantdb.com/docs/auth
155
+ * @throws Error indicating user not signed in
156
+ * @example
157
+ * function UserDisplay() {
158
+ * const user = db.useUser()
159
+ * return <div>Logged in as: {user.email}</div>
160
+ * }
161
+ *
162
+ * <db.SignedIn>
163
+ * <UserDisplay />
164
+ * </db.SignedIn>
165
+ *
166
+ */
167
+ useUser: () => User;
168
+ /**
169
+ * One time query for the logged in state. This is useful
170
+ * for scenarios where you want to know the current auth
171
+ * state without subscribing to changes.
172
+ *
173
+ * @see https://instantdb.com/docs/auth
174
+ * @example
175
+ * const user = await db.getAuth();
176
+ * console.log('logged in as', user.email)
177
+ */
178
+ getAuth(): Promise<User | null>;
179
+ /**
180
+ * Listen for connection status changes to Instant. Use this for things like
181
+ * showing connection state to users
182
+ *
183
+ * @see https://www.instantdb.com/docs/patterns#connection-status
184
+ * @example
185
+ * function App() {
186
+ * const status = db.useConnectionStatus()
187
+ * const connectionState =
188
+ * status === 'connecting' || status === 'opened'
189
+ * ? 'authenticating'
190
+ * : status === 'authenticated'
191
+ * ? 'connected'
192
+ * : status === 'closed'
193
+ * ? 'closed'
194
+ * : status === 'errored'
195
+ * ? 'errored'
196
+ * : 'unexpected state';
197
+ *
198
+ * return <div>Connection state: {connectionState}</div>
199
+ * }
200
+ */
201
+ useConnectionStatus: () => ConnectionStatus;
202
+ /**
203
+ * Observe the app's maintenance-mode state. While read-only, reads and
204
+ * live queries keep working but writes are rejected.
205
+ *
206
+ * @example
207
+ * function App() {
208
+ * const { isLoading, isReadOnly } = db.useAppStatus()
209
+ * if (isLoading) return null
210
+ * if (isReadOnly) return <MaintenanceBanner />
211
+ * // ...
212
+ * }
213
+ */
214
+ useAppStatus: () => AppStatusState;
215
+ /**
216
+ * Use this for one-off queries.
217
+ * Returns local data if available, otherwise fetches from the server.
218
+ * Because we want to avoid stale data, this method will throw an error
219
+ * if the user is offline or there is no active connection to the server.
220
+ *
221
+ * @see https://instantdb.com/docs/instaql
222
+ *
223
+ * @example
224
+ *
225
+ * const resp = await db.queryOnce({ goals: {} });
226
+ * console.log(resp.data.goals)
227
+ */
228
+ queryOnce: <Q extends ValidQuery<Q, Schema>>(query: Q, opts?: InstaQLOptions) => Promise<{
229
+ data: InstaQLResponse<Schema, Q, UseDates>;
230
+ pageInfo: PageInfoResponse<Q>;
231
+ }>;
232
+ /**
233
+ * Subscribe to a query and incrementally load more items
234
+ *
235
+ * Only one top level namespace in the query is allowed.
236
+ *
237
+ * Changing the query or options while the subscription is active will
238
+ * reset the subscription and start over with new data.
239
+ * @example
240
+ * const {
241
+ * data,
242
+ * loadNextPage,
243
+ * canLoadNextPage,
244
+ * } = db.useInfiniteQuery({
245
+ * posts: {
246
+ * $: {
247
+ * limit: 20, // Load 20 posts at a time
248
+ * order: {
249
+ * createdAt: 'desc',
250
+ * },
251
+ * },
252
+ * },
253
+ * });
254
+ */
255
+ useInfiniteQuery: <Q extends ValidQuery<Q, Schema>>(query: Q, opts?: InstaQLOptions) => InfiniteQueryResult<Schema, Q, UseDates>;
256
+ /**
257
+ * Only render children if the user is signed in.
258
+ * @see https://instantdb.com/docs/auth
259
+ *
260
+ * @example
261
+ * <db.SignedIn>
262
+ * <MyComponent />
263
+ * </db.SignedIn>
264
+ *
265
+ */
266
+ SignedIn: React.FC<{
267
+ children: ReactNode;
268
+ }>;
269
+ /**
270
+ * Only render children if the user is signed out.
271
+ * @see https://instantdb.com/docs/auth
272
+ *
273
+ * @example
274
+ * <db.SignedOut>
275
+ * <MyComponent />
276
+ * </db.SignedOut>
277
+ *
278
+ */
279
+ SignedOut: React.FC<{
280
+ children: ReactNode;
281
+ }>;
282
+ }
283
+ //# sourceMappingURL=InstantReactAbstractDatabase.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InstantReactAbstractDatabase.d.ts","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"AACA,OAAO,EAEL,IAAI,EACJ,OAAO,EAEP,KAAK,SAAS,EACd,K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;OAWG;IACH,YAAY,QAAO,cAAc,CAsB/B;IAEF;;;;;;;;;;;;OAYG;IACH,SAAS,GAAI,CAAC,SAAS,UAAU,CAAC,CAAC,EAAE,MAAM,CAAC,EAC1C,OAAO,CAAC,EACR,OAAO,cAAc,KACpB,OAAO,CAAC;QACT,IAAI,EAAE,eAAe,CAAC,MAAM,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;QAC3C,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;KAC/B,CAAC,CAEA;IAEF;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,gBAAgB,GAAI,CAAC,SAAS,UAAU,CAAC,CAAC,EAAE,MAAM,CAAC,EACjD,OAAO,CAAC,EACR,OAAO,cAAc,KACpB,mBAAmB,CAAC,MAAM,EAAE,CAAC,EAAE,QAAQ,CAAC,CAOzC;IAEF;;;;;;;;;OASG;IACH,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC;QACjB,QAAQ,EAAE,SAAS,CAAC;KACrB,CAAC,CAKA;IAEF;;;;;;;;;OASG;IACH,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC;QAClB,QAAQ,EAAE,SAAS,CAAC;KACrB,CAAC,CAIA;CACH"}
@@ -0,0 +1,387 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
3
+ import { txInit, init as core_init, InstantError, } from '@instantdb/core';
4
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore, } from 'react';
5
+ import { useQueryInternal } from "./useQuery.js";
6
+ import { useInfiniteQuerySubscription, } from "./useInfiniteQuerySubscription.js";
7
+ import { InstantReactRoom, rooms } from "./InstantReactRoom.js";
8
+ const defaultAuthState = {
9
+ isLoading: true,
10
+ user: undefined,
11
+ error: undefined,
12
+ };
13
+ const defaultAppStatusState = {
14
+ isLoading: true,
15
+ isReadOnly: undefined,
16
+ };
17
+ export default class InstantReactAbstractDatabase {
18
+ tx = txInit();
19
+ auth;
20
+ storage;
21
+ streams;
22
+ core;
23
+ /** @deprecated use `core` instead */
24
+ _core;
25
+ static Store;
26
+ static NetworkListener;
27
+ static EventSourceImpl;
28
+ constructor(config, versions) {
29
+ this.core = core_init(config,
30
+ // @ts-expect-error because TS can't resolve subclass statics
31
+ config.Store || this.constructor.Store,
32
+ // @ts-expect-error because TS can't resolve subclass statics
33
+ this.constructor.NetworkListener, versions,
34
+ // @ts-expect-error because TS can't resolve subclass statics
35
+ this.constructor.EventSourceImpl);
36
+ this._core = this.core;
37
+ this.auth = this.core.auth;
38
+ this.storage = this.core.storage;
39
+ this.streams = this.core.streams;
40
+ }
41
+ /**
42
+ * Returns a unique ID for a given `name`. It's stored in local storage,
43
+ * so you will get the same ID across sessions.
44
+ *
45
+ * This is useful for generating IDs that could identify a local device or user.
46
+ *
47
+ * @example
48
+ * const deviceId = await db.getLocalId('device');
49
+ */
50
+ getLocalId = (name) => {
51
+ return this.core.getLocalId(name);
52
+ };
53
+ /**
54
+ * A hook that returns a unique ID for a given `name`. localIds are
55
+ * stored in local storage, so you will get the same ID across sessions.
56
+ *
57
+ * Initially returns `null`, and then loads the localId.
58
+ *
59
+ * @example
60
+ * const deviceId = db.useLocalId('device');
61
+ * if (!deviceId) return null; // loading
62
+ * console.log('Device ID:', deviceId)
63
+ */
64
+ useLocalId = (name) => {
65
+ const [localId, setLocalId] = useState(null);
66
+ useEffect(() => {
67
+ let mounted = true;
68
+ const f = async () => {
69
+ const id = await this.getLocalId(name);
70
+ if (!mounted)
71
+ return;
72
+ setLocalId(id);
73
+ };
74
+ f();
75
+ return;
76
+ }, [name]);
77
+ return localId;
78
+ };
79
+ /**
80
+ * Obtain a handle to a room, which allows you to listen to topics and presence data
81
+ *
82
+ * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`
83
+ * as the room type and id, respectively.
84
+ *
85
+ * @see https://instantdb.com/docs/presence-and-topics
86
+ *
87
+ * @example
88
+ * const room = db.room('chat', roomId);
89
+ * const { peers } = db.rooms.usePresence(room);
90
+ */
91
+ room(type = '_defaultRoomType', id = '_defaultRoomId') {
92
+ return new InstantReactRoom(this.core, type, id);
93
+ }
94
+ /**
95
+ * Hooks for working with rooms
96
+ *
97
+ * @see https://instantdb.com/docs/presence-and-topics
98
+ *
99
+ * @example
100
+ * const room = db.room('chat', roomId);
101
+ * const { peers } = db.rooms.usePresence(room);
102
+ * const publish = db.rooms.usePublishTopic(room, 'emoji');
103
+ * // ...
104
+ */
105
+ rooms = rooms;
106
+ /**
107
+ * Use this to write data! You can create, update, delete, and link objects
108
+ *
109
+ * @see https://instantdb.com/docs/instaml
110
+ *
111
+ * @example
112
+ * // Create a new object in the `goals` namespace
113
+ * const goalId = id();
114
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
115
+ *
116
+ * // Update the title
117
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
118
+ *
119
+ * // Delete it
120
+ * db.transact(db.tx.goals[goalId].delete())
121
+ *
122
+ * // Or create an association:
123
+ * todoId = id();
124
+ * db.transact([
125
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
126
+ * db.tx.goals[goalId].link({todos: todoId}),
127
+ * ])
128
+ */
129
+ transact = (chunks) => {
130
+ return this.core.transact(chunks);
131
+ };
132
+ /**
133
+ * Use this to query your data!
134
+ *
135
+ * @see https://instantdb.com/docs/instaql
136
+ *
137
+ * @example
138
+ * // listen to all goals
139
+ * const { isLoading, error, data } = db.useQuery({ goals: {} });
140
+ *
141
+ * // goals where the title is "Get Fit"
142
+ * const { isLoading, error, data } = db.useQuery({
143
+ * goals: { $: { where: { title: 'Get Fit' } } },
144
+ * });
145
+ *
146
+ * // all goals, _alongside_ their todos
147
+ * const { isLoading, error, data } = db.useQuery({
148
+ * goals: { todos: {} },
149
+ * });
150
+ *
151
+ * // skip if `user` is not logged in
152
+ * const { isLoading, error, data } = db.useQuery(
153
+ * auth.user ? { goals: {} } : null,
154
+ * );
155
+ */
156
+ useQuery = (query, opts) => {
157
+ return useQueryInternal(this.core, query, opts).state;
158
+ };
159
+ /**
160
+ * Listen for the logged in state. This is useful
161
+ * for deciding when to show a login screen.
162
+ *
163
+ * Check out the docs for an example `Login` component too!
164
+ *
165
+ * @see https://instantdb.com/docs/auth
166
+ * @example
167
+ * function App() {
168
+ * const { isLoading, user, error } = db.useAuth()
169
+ * if (isLoading) {
170
+ * return <div>Loading...</div>
171
+ * }
172
+ * if (error) {
173
+ * return <div>Uh oh! {error.message}</div>
174
+ * }
175
+ * if (user) {
176
+ * return <Main user={user} />
177
+ * }
178
+ * return <Login />
179
+ * }
180
+ *
181
+ */
182
+ useAuth = () => {
183
+ return this._useAuth();
184
+ };
185
+ _useAuth() {
186
+ // We use a ref to store the result of the query.
187
+ // This is becuase `useSyncExternalStore` uses `Object.is`
188
+ // to compare the previous and next state.
189
+ // If we don't use a ref, the state will always be considered different, so
190
+ // the component will always re-render.
191
+ const resultCacheRef = useRef(this.core._reactor._currentUserCached);
192
+ // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe
193
+ // if `subscribe` changes, so we use `useCallback` to memoize the function.
194
+ const subscribe = useCallback((cb) => {
195
+ const unsubscribe = this.core.subscribeAuth((auth) => {
196
+ resultCacheRef.current = { isLoading: false, ...auth };
197
+ cb();
198
+ });
199
+ return unsubscribe;
200
+ }, []);
201
+ const state = useSyncExternalStore(subscribe, () => resultCacheRef.current, () => defaultAuthState);
202
+ return state;
203
+ }
204
+ /**
205
+ * Subscribe to the currently logged in user.
206
+ * If the user is not logged in, this hook with throw an Error.
207
+ * You will want to protect any calls of this hook with a
208
+ * <db.SignedIn> component, or your own logic based on db.useAuth()
209
+ *
210
+ * @see https://instantdb.com/docs/auth
211
+ * @throws Error indicating user not signed in
212
+ * @example
213
+ * function UserDisplay() {
214
+ * const user = db.useUser()
215
+ * return <div>Logged in as: {user.email}</div>
216
+ * }
217
+ *
218
+ * <db.SignedIn>
219
+ * <UserDisplay />
220
+ * </db.SignedIn>
221
+ *
222
+ */
223
+ useUser = () => {
224
+ const { user } = this.useAuth();
225
+ if (!user) {
226
+ throw new InstantError('useUser must be used within an auth-protected route');
227
+ }
228
+ return user;
229
+ };
230
+ /**
231
+ * One time query for the logged in state. This is useful
232
+ * for scenarios where you want to know the current auth
233
+ * state without subscribing to changes.
234
+ *
235
+ * @see https://instantdb.com/docs/auth
236
+ * @example
237
+ * const user = await db.getAuth();
238
+ * console.log('logged in as', user.email)
239
+ */
240
+ getAuth() {
241
+ return this.core.getAuth();
242
+ }
243
+ /**
244
+ * Listen for connection status changes to Instant. Use this for things like
245
+ * showing connection state to users
246
+ *
247
+ * @see https://www.instantdb.com/docs/patterns#connection-status
248
+ * @example
249
+ * function App() {
250
+ * const status = db.useConnectionStatus()
251
+ * const connectionState =
252
+ * status === 'connecting' || status === 'opened'
253
+ * ? 'authenticating'
254
+ * : status === 'authenticated'
255
+ * ? 'connected'
256
+ * : status === 'closed'
257
+ * ? 'closed'
258
+ * : status === 'errored'
259
+ * ? 'errored'
260
+ * : 'unexpected state';
261
+ *
262
+ * return <div>Connection state: {connectionState}</div>
263
+ * }
264
+ */
265
+ useConnectionStatus = () => {
266
+ const statusRef = useRef(this.core._reactor.status);
267
+ const subscribe = useCallback((cb) => {
268
+ const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {
269
+ if (newStatus !== statusRef.current) {
270
+ statusRef.current = newStatus;
271
+ cb();
272
+ }
273
+ });
274
+ return unsubscribe;
275
+ }, []);
276
+ const status = useSyncExternalStore(subscribe, () => statusRef.current,
277
+ // For SSR, always return 'connecting' as the initial state
278
+ () => 'connecting');
279
+ return status;
280
+ };
281
+ /**
282
+ * Observe the app's maintenance-mode state. While read-only, reads and
283
+ * live queries keep working but writes are rejected.
284
+ *
285
+ * @example
286
+ * function App() {
287
+ * const { isLoading, isReadOnly } = db.useAppStatus()
288
+ * if (isLoading) return null
289
+ * if (isReadOnly) return <MaintenanceBanner />
290
+ * // ...
291
+ * }
292
+ */
293
+ useAppStatus = () => {
294
+ const stateRef = useRef(this.core._reactor._appStatusState);
295
+ const subscribe = useCallback((cb) => {
296
+ return this.core.subscribeAppStatus((state) => {
297
+ if (state.isLoading !== stateRef.current.isLoading ||
298
+ state.isReadOnly !== stateRef.current.isReadOnly) {
299
+ stateRef.current = state;
300
+ cb();
301
+ }
302
+ });
303
+ }, []);
304
+ const state = useSyncExternalStore(subscribe, () => stateRef.current, () => defaultAppStatusState);
305
+ return state;
306
+ };
307
+ /**
308
+ * Use this for one-off queries.
309
+ * Returns local data if available, otherwise fetches from the server.
310
+ * Because we want to avoid stale data, this method will throw an error
311
+ * if the user is offline or there is no active connection to the server.
312
+ *
313
+ * @see https://instantdb.com/docs/instaql
314
+ *
315
+ * @example
316
+ *
317
+ * const resp = await db.queryOnce({ goals: {} });
318
+ * console.log(resp.data.goals)
319
+ */
320
+ queryOnce = (query, opts) => {
321
+ return this.core.queryOnce(query, opts);
322
+ };
323
+ /**
324
+ * Subscribe to a query and incrementally load more items
325
+ *
326
+ * Only one top level namespace in the query is allowed.
327
+ *
328
+ * Changing the query or options while the subscription is active will
329
+ * reset the subscription and start over with new data.
330
+ * @example
331
+ * const {
332
+ * data,
333
+ * loadNextPage,
334
+ * canLoadNextPage,
335
+ * } = db.useInfiniteQuery({
336
+ * posts: {
337
+ * $: {
338
+ * limit: 20, // Load 20 posts at a time
339
+ * order: {
340
+ * createdAt: 'desc',
341
+ * },
342
+ * },
343
+ * },
344
+ * });
345
+ */
346
+ useInfiniteQuery = (query, opts) => {
347
+ const result = useInfiniteQuerySubscription({
348
+ core: this.core,
349
+ query: query,
350
+ opts,
351
+ });
352
+ return result;
353
+ };
354
+ /**
355
+ * Only render children if the user is signed in.
356
+ * @see https://instantdb.com/docs/auth
357
+ *
358
+ * @example
359
+ * <db.SignedIn>
360
+ * <MyComponent />
361
+ * </db.SignedIn>
362
+ *
363
+ */
364
+ SignedIn = ({ children }) => {
365
+ const auth = this.useAuth();
366
+ if (auth.isLoading || auth.error || !auth.user)
367
+ return null;
368
+ return _jsx(_Fragment, { children: children });
369
+ };
370
+ /**
371
+ * Only render children if the user is signed out.
372
+ * @see https://instantdb.com/docs/auth
373
+ *
374
+ * @example
375
+ * <db.SignedOut>
376
+ * <MyComponent />
377
+ * </db.SignedOut>
378
+ *
379
+ */
380
+ SignedOut = ({ children }) => {
381
+ const auth = this.useAuth();
382
+ if (auth.isLoading || auth.error || auth.user)
383
+ return null;
384
+ return _jsx(_Fragment, { children: children });
385
+ };
386
+ }
387
+ //# sourceMappingURL=InstantReactAbstractDatabase.js.map