@instantdb/react-common 0.22.15-experimental.react-common.18536829600.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 (65) 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/README.md +53 -0
  5. package/dist/commonjs/InstantReactAbstractDatabase.d.ts +241 -0
  6. package/dist/commonjs/InstantReactAbstractDatabase.d.ts.map +1 -0
  7. package/dist/commonjs/InstantReactAbstractDatabase.js +323 -0
  8. package/dist/commonjs/InstantReactAbstractDatabase.js.map +1 -0
  9. package/dist/commonjs/InstantReactRoom.d.ts +183 -0
  10. package/dist/commonjs/InstantReactRoom.d.ts.map +1 -0
  11. package/dist/commonjs/InstantReactRoom.js +284 -0
  12. package/dist/commonjs/InstantReactRoom.js.map +1 -0
  13. package/dist/commonjs/index.d.ts +4 -0
  14. package/dist/commonjs/index.d.ts.map +1 -0
  15. package/dist/commonjs/index.js +9 -0
  16. package/dist/commonjs/index.js.map +1 -0
  17. package/dist/commonjs/package.json +3 -0
  18. package/dist/commonjs/useQuery.d.ts +6 -0
  19. package/dist/commonjs/useQuery.d.ts.map +1 -0
  20. package/dist/commonjs/useQuery.js +48 -0
  21. package/dist/commonjs/useQuery.js.map +1 -0
  22. package/dist/commonjs/useTimeout.d.ts +5 -0
  23. package/dist/commonjs/useTimeout.d.ts.map +1 -0
  24. package/dist/commonjs/useTimeout.js +19 -0
  25. package/dist/commonjs/useTimeout.js.map +1 -0
  26. package/dist/commonjs/version.d.ts +3 -0
  27. package/dist/commonjs/version.d.ts.map +1 -0
  28. package/dist/commonjs/version.js +5 -0
  29. package/dist/commonjs/version.js.map +1 -0
  30. package/dist/esm/InstantReactAbstractDatabase.d.ts +241 -0
  31. package/dist/esm/InstantReactAbstractDatabase.d.ts.map +1 -0
  32. package/dist/esm/InstantReactAbstractDatabase.js +320 -0
  33. package/dist/esm/InstantReactAbstractDatabase.js.map +1 -0
  34. package/dist/esm/InstantReactRoom.d.ts +183 -0
  35. package/dist/esm/InstantReactRoom.d.ts.map +1 -0
  36. package/dist/esm/InstantReactRoom.js +275 -0
  37. package/dist/esm/InstantReactRoom.js.map +1 -0
  38. package/dist/esm/index.d.ts +4 -0
  39. package/dist/esm/index.d.ts.map +1 -0
  40. package/dist/esm/index.js +3 -0
  41. package/dist/esm/index.js.map +1 -0
  42. package/dist/esm/package.json +3 -0
  43. package/dist/esm/useQuery.d.ts +6 -0
  44. package/dist/esm/useQuery.d.ts.map +1 -0
  45. package/dist/esm/useQuery.js +45 -0
  46. package/dist/esm/useQuery.js.map +1 -0
  47. package/dist/esm/useTimeout.d.ts +5 -0
  48. package/dist/esm/useTimeout.d.ts.map +1 -0
  49. package/dist/esm/useTimeout.js +16 -0
  50. package/dist/esm/useTimeout.js.map +1 -0
  51. package/dist/esm/version.d.ts +3 -0
  52. package/dist/esm/version.d.ts.map +1 -0
  53. package/dist/esm/version.js +3 -0
  54. package/dist/esm/version.js.map +1 -0
  55. package/dist/standalone/index.js +5993 -0
  56. package/dist/standalone/index.umd.cjs +36 -0
  57. package/package.json +68 -0
  58. package/src/InstantReactAbstractDatabase.tsx +421 -0
  59. package/src/InstantReactRoom.ts +443 -0
  60. package/src/index.ts +4 -0
  61. package/src/useQuery.ts +99 -0
  62. package/src/useTimeout.ts +20 -0
  63. package/src/version.ts +3 -0
  64. package/tsconfig.json +11 -0
  65. package/vite.config.ts +35 -0
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "../src",
5
+ "module": "nodenext",
6
+ "moduleResolution": "nodenext"
7
+ }
8
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": "./build.json",
3
+ "include": [
4
+ "../src/**/*.ts",
5
+ "../src/**/*.cts",
6
+ "../src/**/*.tsx",
7
+ "../src/**/*.json"
8
+ ],
9
+ "exclude": [
10
+ "../src/**/*.mts",
11
+ "../src/package.json"
12
+ ],
13
+ "compilerOptions": {
14
+ "outDir": "../.tshy-build/commonjs"
15
+ }
16
+ }
package/.tshy/esm.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "./build.json",
3
+ "include": [
4
+ "../src/**/*.ts",
5
+ "../src/**/*.mts",
6
+ "../src/**/*.tsx",
7
+ "../src/**/*.json"
8
+ ],
9
+ "exclude": [
10
+ "../src/package.json"
11
+ ],
12
+ "compilerOptions": {
13
+ "outDir": "../.tshy-build/esm"
14
+ }
15
+ }
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ <p align="center">
2
+ <a href="https://instantdb.com">
3
+ <img alt="Shows the Instant logo" src="https://instantdb.com/img/icon/android-chrome-512x512.png" width="10%">
4
+ </a>
5
+ <h1 align="center">@instantdb/react-common</h1>
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a
10
+ href="https://discord.com/invite/VU53p7uQcE" >
11
+ <img height=20 src="https://img.shields.io/discord/1031957483243188235" />
12
+ </a>
13
+ <img src="https://img.shields.io/github/stars/instantdb/instant" alt="stars">
14
+ </p>
15
+
16
+ <p align="center">
17
+ <a href="https://instantdb.com/dash">Get Started</a> ·
18
+ <a href="https://instantdb.com/examples">Examples</a> ·
19
+ <a href="https://instantdb.com/docs">Docs</a> ·
20
+ <a href="https://discord.com/invite/VU53p7uQcE">Discord</a>
21
+ <p>
22
+
23
+ Welcome to [Instant's](http://instantdb.com) React common components for React and React Native.
24
+
25
+ ```javascript
26
+ // ༼ つ ◕_◕ ༽つ Real-time Chat
27
+ // ----------------------------------
28
+ // * Updates instantly
29
+ // * Multiplayer
30
+ // * Works offline
31
+ function Chat() {
32
+ // 1. Read
33
+ const { isLoading, error, data } = useQuery({
34
+ messages: {},
35
+ });
36
+
37
+ // 2. Write
38
+ const addMessage = (message) => {
39
+ transact(tx.messages[id()].update(message));
40
+ };
41
+
42
+ // 3. Render!
43
+ return <UI data={data} onAdd={addMessage} />;
44
+ }
45
+ ```
46
+
47
+ # Get Started
48
+
49
+ Follow the [getting started](https://www.instantdb.com/docs) tutorial to set up a live React app in under 5 minutes!
50
+
51
+ # Questions?
52
+
53
+ If you have any questions, feel free to drop us a line on our [Discord](https://discord.com/invite/VU53p7uQcE)
@@ -0,0 +1,241 @@
1
+ import { Auth, Storage, type AuthState, type User, type ConnectionStatus, type TransactionChunk, type RoomSchemaShape, type InstaQLOptions, type InstantConfig, type PageInfoResponse, InstantCoreDatabase, InstaQLLifecycleState, InstaQLResponse, RoomsOf, InstantSchemaDef, IInstantDatabase, ValidQuery } from '@instantdb/core';
2
+ import { ReactNode } from 'react';
3
+ import { InstantReactRoom } from './InstantReactRoom.ts';
4
+ export default abstract class InstantReactAbstractDatabase<Schema extends InstantSchemaDef<any, any, any>, Config extends InstantConfig<Schema, boolean> = InstantConfig<Schema, false>, Rooms extends RoomSchemaShape = RoomsOf<Schema>> implements IInstantDatabase<Schema> {
5
+ tx: import("@instantdb/core").TxChunk<Schema>;
6
+ auth: Auth;
7
+ storage: Storage;
8
+ core: InstantCoreDatabase<Schema, Config['useDateObjects']>;
9
+ /** @deprecated use `core` instead */
10
+ _core: InstantCoreDatabase<Schema, Config['useDateObjects']>;
11
+ static Storage?: any;
12
+ static NetworkListener?: any;
13
+ static EventSourceImpl?: any;
14
+ constructor(config: Config, versions?: {
15
+ [key: string]: string;
16
+ });
17
+ /**
18
+ * Returns a unique ID for a given `name`. It's stored in local storage,
19
+ * so you will get the same ID across sessions.
20
+ *
21
+ * This is useful for generating IDs that could identify a local device or user.
22
+ *
23
+ * @example
24
+ * const deviceId = await db.getLocalId('device');
25
+ */
26
+ getLocalId: (name: string) => Promise<string>;
27
+ /**
28
+ * A hook that returns a unique ID for a given `name`. localIds are
29
+ * stored in local storage, so you will get the same ID across sessions.
30
+ *
31
+ * Initially returns `null`, and then loads the localId.
32
+ *
33
+ * @example
34
+ * const deviceId = db.useLocalId('device');
35
+ * if (!deviceId) return null; // loading
36
+ * console.log('Device ID:', deviceId)
37
+ */
38
+ useLocalId: (name: string) => string | null;
39
+ /**
40
+ * Obtain a handle to a room, which allows you to listen to topics and presence data
41
+ *
42
+ * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`
43
+ * as the room type and id, respectively.
44
+ *
45
+ * @see https://instantdb.com/docs/presence-and-topics
46
+ *
47
+ * @example
48
+ * const room = db.room('chat', roomId);
49
+ * const { peers } = db.rooms.usePresence(room);
50
+ */
51
+ room<RoomType extends keyof Rooms>(type?: RoomType, id?: string): InstantReactRoom<Schema, Rooms, RoomType>;
52
+ /**
53
+ * Hooks for working with rooms
54
+ *
55
+ * @see https://instantdb.com/docs/presence-and-topics
56
+ *
57
+ * @example
58
+ * const room = db.room('chat', roomId);
59
+ * const { peers } = db.rooms.usePresence(room);
60
+ * const publish = db.rooms.usePublishTopic(room, 'emoji');
61
+ * // ...
62
+ */
63
+ rooms: {
64
+ useTopicEffect: typeof import("./InstantReactRoom.ts").useTopicEffect;
65
+ usePublishTopic: typeof import("./InstantReactRoom.ts").usePublishTopic;
66
+ usePresence: typeof import("./InstantReactRoom.ts").usePresence;
67
+ useSyncPresence: typeof import("./InstantReactRoom.ts").useSyncPresence;
68
+ useTypingIndicator: typeof import("./InstantReactRoom.ts").useTypingIndicator;
69
+ };
70
+ /**
71
+ * Use this to write data! You can create, update, delete, and link objects
72
+ *
73
+ * @see https://instantdb.com/docs/instaml
74
+ *
75
+ * @example
76
+ * // Create a new object in the `goals` namespace
77
+ * const goalId = id();
78
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
79
+ *
80
+ * // Update the title
81
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
82
+ *
83
+ * // Delete it
84
+ * db.transact(db.tx.goals[goalId].delete())
85
+ *
86
+ * // Or create an association:
87
+ * todoId = id();
88
+ * db.transact([
89
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
90
+ * db.tx.goals[goalId].link({todos: todoId}),
91
+ * ])
92
+ */
93
+ transact: (chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[]) => Promise<import("@instantdb/core").TransactionResult>;
94
+ /**
95
+ * Use this to query your data!
96
+ *
97
+ * @see https://instantdb.com/docs/instaql
98
+ *
99
+ * @example
100
+ * // listen to all goals
101
+ * const { isLoading, error, data } = db.useQuery({ goals: {} });
102
+ *
103
+ * // goals where the title is "Get Fit"
104
+ * const { isLoading, error, data } = db.useQuery({
105
+ * goals: { $: { where: { title: 'Get Fit' } } },
106
+ * });
107
+ *
108
+ * // all goals, _alongside_ their todos
109
+ * const { isLoading, error, data } = db.useQuery({
110
+ * goals: { todos: {} },
111
+ * });
112
+ *
113
+ * // skip if `user` is not logged in
114
+ * const { isLoading, error, data } = db.useQuery(
115
+ * auth.user ? { goals: {} } : null,
116
+ * );
117
+ */
118
+ useQuery: <Q extends ValidQuery<Q, Schema>>(query: null | Q, opts?: InstaQLOptions) => InstaQLLifecycleState<Schema, Q, NonNullable<Config["useDateObjects"]>>;
119
+ /**
120
+ * Listen for the logged in state. This is useful
121
+ * for deciding when to show a login screen.
122
+ *
123
+ * Check out the docs for an example `Login` component too!
124
+ *
125
+ * @see https://instantdb.com/docs/auth
126
+ * @example
127
+ * function App() {
128
+ * const { isLoading, user, error } = db.useAuth()
129
+ * if (isLoading) {
130
+ * return <div>Loading...</div>
131
+ * }
132
+ * if (error) {
133
+ * return <div>Uh oh! {error.message}</div>
134
+ * }
135
+ * if (user) {
136
+ * return <Main user={user} />
137
+ * }
138
+ * return <Login />
139
+ * }
140
+ *
141
+ */
142
+ useAuth: () => AuthState;
143
+ /**
144
+ * Subscribe to the currently logged in user.
145
+ * If the user is not logged in, this hook with throw an Error.
146
+ * You will want to protect any calls of this hook with a
147
+ * <db.SignedIn> component, or your own logic based on db.useAuth()
148
+ *
149
+ * @see https://instantdb.com/docs/auth
150
+ * @throws Error indicating user not signed in
151
+ * @example
152
+ * function UserDisplay() {
153
+ * const user = db.useUser()
154
+ * return <div>Logged in as: {user.email}</div>
155
+ * }
156
+ *
157
+ * <db.SignedIn>
158
+ * <UserDisplay />
159
+ * </db.SignedIn>
160
+ *
161
+ */
162
+ useUser: () => User;
163
+ /**
164
+ * One time query for the logged in state. This is useful
165
+ * for scenarios where you want to know the current auth
166
+ * state without subscribing to changes.
167
+ *
168
+ * @see https://instantdb.com/docs/auth
169
+ * @example
170
+ * const user = await db.getAuth();
171
+ * console.log('logged in as', user.email)
172
+ */
173
+ getAuth(): Promise<User | null>;
174
+ /**
175
+ * Listen for connection status changes to Instant. Use this for things like
176
+ * showing connection state to users
177
+ *
178
+ * @see https://www.instantdb.com/docs/patterns#connection-status
179
+ * @example
180
+ * function App() {
181
+ * const status = db.useConnectionStatus()
182
+ * const connectionState =
183
+ * status === 'connecting' || status === 'opened'
184
+ * ? 'authenticating'
185
+ * : status === 'authenticated'
186
+ * ? 'connected'
187
+ * : status === 'closed'
188
+ * ? 'closed'
189
+ * : status === 'errored'
190
+ * ? 'errored'
191
+ * : 'unexpected state';
192
+ *
193
+ * return <div>Connection state: {connectionState}</div>
194
+ * }
195
+ */
196
+ useConnectionStatus: () => ConnectionStatus;
197
+ /**
198
+ * Use this for one-off queries.
199
+ * Returns local data if available, otherwise fetches from the server.
200
+ * Because we want to avoid stale data, this method will throw an error
201
+ * if the user is offline or there is no active connection to the server.
202
+ *
203
+ * @see https://instantdb.com/docs/instaql
204
+ *
205
+ * @example
206
+ *
207
+ * const resp = await db.queryOnce({ goals: {} });
208
+ * console.log(resp.data.goals)
209
+ */
210
+ queryOnce: <Q extends ValidQuery<Q, Schema>>(query: Q, opts?: InstaQLOptions) => Promise<{
211
+ data: InstaQLResponse<Schema, Q, Config["useDateObjects"]>;
212
+ pageInfo: PageInfoResponse<Q>;
213
+ }>;
214
+ /**
215
+ * Only render children if the user is signed in.
216
+ * @see https://instantdb.com/docs/auth
217
+ *
218
+ * @example
219
+ * <db.SignedIn>
220
+ * <MyComponent />
221
+ * </db.SignedIn>
222
+ *
223
+ */
224
+ SignedIn: React.FC<{
225
+ children: ReactNode;
226
+ }>;
227
+ /**
228
+ * Only render children if the user is signed out.
229
+ * @see https://instantdb.com/docs/auth
230
+ *
231
+ * @example
232
+ * <db.SignedOut>
233
+ * <MyComponent />
234
+ * </db.SignedOut>
235
+ *
236
+ */
237
+ SignedOut: React.FC<{
238
+ children: ReactNode;
239
+ }>;
240
+ }
241
+ //# sourceMappingURL=InstantReactAbstractDatabase.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InstantReactAbstractDatabase.d.ts","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"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"}
@@ -0,0 +1,323 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const jsx_runtime_1 = require("react/jsx-runtime");
13
+ const core_1 = require("@instantdb/core");
14
+ const react_1 = require("react");
15
+ const useQuery_ts_1 = require("./useQuery.js");
16
+ const InstantReactRoom_ts_1 = require("./InstantReactRoom.js");
17
+ const defaultAuthState = {
18
+ isLoading: true,
19
+ user: undefined,
20
+ error: undefined,
21
+ };
22
+ class InstantReactAbstractDatabase {
23
+ constructor(config, versions) {
24
+ this.tx = (0, core_1.txInit)();
25
+ /**
26
+ * Returns a unique ID for a given `name`. It's stored in local storage,
27
+ * so you will get the same ID across sessions.
28
+ *
29
+ * This is useful for generating IDs that could identify a local device or user.
30
+ *
31
+ * @example
32
+ * const deviceId = await db.getLocalId('device');
33
+ */
34
+ this.getLocalId = (name) => {
35
+ return this.core.getLocalId(name);
36
+ };
37
+ /**
38
+ * A hook that returns a unique ID for a given `name`. localIds are
39
+ * stored in local storage, so you will get the same ID across sessions.
40
+ *
41
+ * Initially returns `null`, and then loads the localId.
42
+ *
43
+ * @example
44
+ * const deviceId = db.useLocalId('device');
45
+ * if (!deviceId) return null; // loading
46
+ * console.log('Device ID:', deviceId)
47
+ */
48
+ this.useLocalId = (name) => {
49
+ const [localId, setLocalId] = (0, react_1.useState)(null);
50
+ (0, react_1.useEffect)(() => {
51
+ let mounted = true;
52
+ const f = () => __awaiter(this, void 0, void 0, function* () {
53
+ const id = yield this.getLocalId(name);
54
+ if (!mounted)
55
+ return;
56
+ setLocalId(id);
57
+ });
58
+ f();
59
+ return;
60
+ }, [name]);
61
+ return localId;
62
+ };
63
+ /**
64
+ * Hooks for working with rooms
65
+ *
66
+ * @see https://instantdb.com/docs/presence-and-topics
67
+ *
68
+ * @example
69
+ * const room = db.room('chat', roomId);
70
+ * const { peers } = db.rooms.usePresence(room);
71
+ * const publish = db.rooms.usePublishTopic(room, 'emoji');
72
+ * // ...
73
+ */
74
+ this.rooms = InstantReactRoom_ts_1.rooms;
75
+ /**
76
+ * Use this to write data! You can create, update, delete, and link objects
77
+ *
78
+ * @see https://instantdb.com/docs/instaml
79
+ *
80
+ * @example
81
+ * // Create a new object in the `goals` namespace
82
+ * const goalId = id();
83
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
84
+ *
85
+ * // Update the title
86
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
87
+ *
88
+ * // Delete it
89
+ * db.transact(db.tx.goals[goalId].delete())
90
+ *
91
+ * // Or create an association:
92
+ * todoId = id();
93
+ * db.transact([
94
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
95
+ * db.tx.goals[goalId].link({todos: todoId}),
96
+ * ])
97
+ */
98
+ this.transact = (chunks) => {
99
+ return this.core.transact(chunks);
100
+ };
101
+ /**
102
+ * Use this to query your data!
103
+ *
104
+ * @see https://instantdb.com/docs/instaql
105
+ *
106
+ * @example
107
+ * // listen to all goals
108
+ * const { isLoading, error, data } = db.useQuery({ goals: {} });
109
+ *
110
+ * // goals where the title is "Get Fit"
111
+ * const { isLoading, error, data } = db.useQuery({
112
+ * goals: { $: { where: { title: 'Get Fit' } } },
113
+ * });
114
+ *
115
+ * // all goals, _alongside_ their todos
116
+ * const { isLoading, error, data } = db.useQuery({
117
+ * goals: { todos: {} },
118
+ * });
119
+ *
120
+ * // skip if `user` is not logged in
121
+ * const { isLoading, error, data } = db.useQuery(
122
+ * auth.user ? { goals: {} } : null,
123
+ * );
124
+ */
125
+ this.useQuery = (query, opts) => {
126
+ return (0, useQuery_ts_1.useQueryInternal)(this.core, query, opts).state;
127
+ };
128
+ /**
129
+ * Listen for the logged in state. This is useful
130
+ * for deciding when to show a login screen.
131
+ *
132
+ * Check out the docs for an example `Login` component too!
133
+ *
134
+ * @see https://instantdb.com/docs/auth
135
+ * @example
136
+ * function App() {
137
+ * const { isLoading, user, error } = db.useAuth()
138
+ * if (isLoading) {
139
+ * return <div>Loading...</div>
140
+ * }
141
+ * if (error) {
142
+ * return <div>Uh oh! {error.message}</div>
143
+ * }
144
+ * if (user) {
145
+ * return <Main user={user} />
146
+ * }
147
+ * return <Login />
148
+ * }
149
+ *
150
+ */
151
+ this.useAuth = () => {
152
+ // We use a ref to store the result of the query.
153
+ // This is becuase `useSyncExternalStore` uses `Object.is`
154
+ // to compare the previous and next state.
155
+ // If we don't use a ref, the state will always be considered different, so
156
+ // the component will always re-render.
157
+ const resultCacheRef = (0, react_1.useRef)(this.core._reactor._currentUserCached);
158
+ // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe
159
+ // if `subscribe` changes, so we use `useCallback` to memoize the function.
160
+ const subscribe = (0, react_1.useCallback)((cb) => {
161
+ const unsubscribe = this.core.subscribeAuth((auth) => {
162
+ resultCacheRef.current = Object.assign({ isLoading: false }, auth);
163
+ cb();
164
+ });
165
+ return unsubscribe;
166
+ }, []);
167
+ const state = (0, react_1.useSyncExternalStore)(subscribe, () => resultCacheRef.current, () => defaultAuthState);
168
+ return state;
169
+ };
170
+ /**
171
+ * Subscribe to the currently logged in user.
172
+ * If the user is not logged in, this hook with throw an Error.
173
+ * You will want to protect any calls of this hook with a
174
+ * <db.SignedIn> component, or your own logic based on db.useAuth()
175
+ *
176
+ * @see https://instantdb.com/docs/auth
177
+ * @throws Error indicating user not signed in
178
+ * @example
179
+ * function UserDisplay() {
180
+ * const user = db.useUser()
181
+ * return <div>Logged in as: {user.email}</div>
182
+ * }
183
+ *
184
+ * <db.SignedIn>
185
+ * <UserDisplay />
186
+ * </db.SignedIn>
187
+ *
188
+ */
189
+ this.useUser = () => {
190
+ const { user } = this.useAuth();
191
+ if (!user) {
192
+ throw new core_1.InstantError('useUser must be used within an auth-protected route');
193
+ }
194
+ return user;
195
+ };
196
+ /**
197
+ * Listen for connection status changes to Instant. Use this for things like
198
+ * showing connection state to users
199
+ *
200
+ * @see https://www.instantdb.com/docs/patterns#connection-status
201
+ * @example
202
+ * function App() {
203
+ * const status = db.useConnectionStatus()
204
+ * const connectionState =
205
+ * status === 'connecting' || status === 'opened'
206
+ * ? 'authenticating'
207
+ * : status === 'authenticated'
208
+ * ? 'connected'
209
+ * : status === 'closed'
210
+ * ? 'closed'
211
+ * : status === 'errored'
212
+ * ? 'errored'
213
+ * : 'unexpected state';
214
+ *
215
+ * return <div>Connection state: {connectionState}</div>
216
+ * }
217
+ */
218
+ this.useConnectionStatus = () => {
219
+ const statusRef = (0, react_1.useRef)(this.core._reactor.status);
220
+ const subscribe = (0, react_1.useCallback)((cb) => {
221
+ const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {
222
+ if (newStatus !== statusRef.current) {
223
+ statusRef.current = newStatus;
224
+ cb();
225
+ }
226
+ });
227
+ return unsubscribe;
228
+ }, []);
229
+ const status = (0, react_1.useSyncExternalStore)(subscribe, () => statusRef.current,
230
+ // For SSR, always return 'connecting' as the initial state
231
+ () => 'connecting');
232
+ return status;
233
+ };
234
+ /**
235
+ * Use this for one-off queries.
236
+ * Returns local data if available, otherwise fetches from the server.
237
+ * Because we want to avoid stale data, this method will throw an error
238
+ * if the user is offline or there is no active connection to the server.
239
+ *
240
+ * @see https://instantdb.com/docs/instaql
241
+ *
242
+ * @example
243
+ *
244
+ * const resp = await db.queryOnce({ goals: {} });
245
+ * console.log(resp.data.goals)
246
+ */
247
+ this.queryOnce = (query, opts) => {
248
+ return this.core.queryOnce(query, opts);
249
+ };
250
+ /**
251
+ * Only render children if the user is signed in.
252
+ * @see https://instantdb.com/docs/auth
253
+ *
254
+ * @example
255
+ * <db.SignedIn>
256
+ * <MyComponent />
257
+ * </db.SignedIn>
258
+ *
259
+ */
260
+ this.SignedIn = ({ children }) => {
261
+ const auth = this.useAuth();
262
+ if (auth.isLoading || auth.error || !auth.user)
263
+ return null;
264
+ return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: children });
265
+ };
266
+ /**
267
+ * Only render children if the user is signed out.
268
+ * @see https://instantdb.com/docs/auth
269
+ *
270
+ * @example
271
+ * <db.SignedOut>
272
+ * <MyComponent />
273
+ * </db.SignedOut>
274
+ *
275
+ */
276
+ this.SignedOut = ({ children }) => {
277
+ const auth = this.useAuth();
278
+ if (auth.isLoading || auth.error || auth.user)
279
+ return null;
280
+ return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: children });
281
+ };
282
+ this.core = (0, core_1.init)(config,
283
+ // @ts-expect-error because TS can't resolve subclass statics
284
+ this.constructor.Storage,
285
+ // @ts-expect-error because TS can't resolve subclass statics
286
+ this.constructor.NetworkListener, versions,
287
+ // @ts-expect-error because TS can't resolve subclass statics
288
+ this.constructor.EventSourceImpl);
289
+ this._core = this.core;
290
+ this.auth = this.core.auth;
291
+ this.storage = this.core.storage;
292
+ }
293
+ /**
294
+ * Obtain a handle to a room, which allows you to listen to topics and presence data
295
+ *
296
+ * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`
297
+ * as the room type and id, respectively.
298
+ *
299
+ * @see https://instantdb.com/docs/presence-and-topics
300
+ *
301
+ * @example
302
+ * const room = db.room('chat', roomId);
303
+ * const { peers } = db.rooms.usePresence(room);
304
+ */
305
+ room(type = '_defaultRoomType', id = '_defaultRoomId') {
306
+ return new InstantReactRoom_ts_1.InstantReactRoom(this.core, type, id);
307
+ }
308
+ /**
309
+ * One time query for the logged in state. This is useful
310
+ * for scenarios where you want to know the current auth
311
+ * state without subscribing to changes.
312
+ *
313
+ * @see https://instantdb.com/docs/auth
314
+ * @example
315
+ * const user = await db.getAuth();
316
+ * console.log('logged in as', user.email)
317
+ */
318
+ getAuth() {
319
+ return this.core.getAuth();
320
+ }
321
+ }
322
+ exports.default = InstantReactAbstractDatabase;
323
+ //# sourceMappingURL=InstantReactAbstractDatabase.js.map