@instantdb/react-common 1.0.50 → 1.0.51-branch-optional-async-storage.29876965683.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.
@@ -1,4 +1,4 @@
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, Streams } from '@instantdb/core';
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
2
  import { ReactNode } from 'react';
3
3
  import { type InfiniteQueryResult } from './useInfiniteQuerySubscription.ts';
4
4
  import { InstantReactRoom } from './InstantReactRoom.ts';
@@ -199,6 +199,19 @@ export default abstract class InstantReactAbstractDatabase<Schema extends Instan
199
199
  * }
200
200
  */
201
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;
202
215
  /**
203
216
  * Use this for one-off queries.
204
217
  * Returns local data if available, otherwise fetches from the server.
@@ -1 +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,KAAK,IAA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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"}
1
+ {"version":3,"file":"InstantReactAbstractDatabase.d.ts","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"AACA,OAAO,EAEL,IAAI,EACJ,OAAO,EAEP,KAAK,SAAS,EACd,KAAK,IAAI,EACT,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,mBAAmB,EAEnB,qBAAqB,EACrB,eAAe,EACf,OAAO,EACP,gBAAgB,EAChB,gBAAgB,EAEhB,UAAU,EACV,OAAO,EACR,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,SAAS,EAMV,MAAM,OAAO,CAAC;AAEf,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EA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S,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"}
@@ -12,6 +12,10 @@ const defaultAuthState = {
12
12
  user: undefined,
13
13
  error: undefined,
14
14
  };
15
+ const defaultAppStatusState = {
16
+ isLoading: true,
17
+ isReadOnly: undefined,
18
+ };
15
19
  class InstantReactAbstractDatabase {
16
20
  tx = (0, core_1.txInit)();
17
21
  auth;
@@ -276,6 +280,32 @@ class InstantReactAbstractDatabase {
276
280
  () => 'connecting');
277
281
  return status;
278
282
  };
283
+ /**
284
+ * Observe the app's maintenance-mode state. While read-only, reads and
285
+ * live queries keep working but writes are rejected.
286
+ *
287
+ * @example
288
+ * function App() {
289
+ * const { isLoading, isReadOnly } = db.useAppStatus()
290
+ * if (isLoading) return null
291
+ * if (isReadOnly) return <MaintenanceBanner />
292
+ * // ...
293
+ * }
294
+ */
295
+ useAppStatus = () => {
296
+ const stateRef = (0, react_1.useRef)(this.core._reactor._appStatusState);
297
+ const subscribe = (0, react_1.useCallback)((cb) => {
298
+ return this.core.subscribeAppStatus((state) => {
299
+ if (state.isLoading !== stateRef.current.isLoading ||
300
+ state.isReadOnly !== stateRef.current.isReadOnly) {
301
+ stateRef.current = state;
302
+ cb();
303
+ }
304
+ });
305
+ }, []);
306
+ const state = (0, react_1.useSyncExternalStore)(subscribe, () => stateRef.current, () => defaultAppStatusState);
307
+ return state;
308
+ };
279
309
  /**
280
310
  * Use this for one-off queries.
281
311
  * Returns local data if available, otherwise fetches from the server.
@@ -1 +1 @@
1
- {"version":3,"file":"InstantReactAbstractDatabase.js","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;AACb,0CAuByB;AACzB,iCAOe;AACf,+CAAiD;AACjD,uFAG2C;AAC3C,+DAAgE;AAEhE,MAAM,gBAAgB,GAAG;IACvB,SAAS,EAAE,IAAI;IACf,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,SAAS;CACjB,CAAC;AAEF,MAA8B,4BAA4B;IAWjD,EAAE,GAAG,IAAA,aAAM,GAAU,CAAC;IAEtB,IAAI,CAAO;IACX,OAAO,CAAU;IACjB,OAAO,CAAU;IACjB,IAAI,CAAwC;IAEnD,qCAAqC;IAC9B,KAAK,CAAwC;IAEpD,MAAM,CAAC,KAAK,CAAO;IACnB,MAAM,CAAC,eAAe,CAAO;IAC7B,MAAM,CAAC,eAAe,CAAO;IAE7B,YACE,MAEC,EACD,QAAoC;QAEpC,IAAI,CAAC,IAAI,GAAG,IAAA,WAAS,EACnB,MAAM;QACN,6DAA6D;QAC7D,MAAM,CAAC,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,KAAK;QACtC,6DAA6D;QAC7D,IAAI,CAAC,WAAW,CAAC,eAAe,EAChC,QAAQ;QACR,6DAA6D;QAC7D,IAAI,CAAC,WAAW,CAAC,eAAe,CACjC,CAAC;QACF,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;QACjC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;IACnC,CAAC;IAED;;;;;;;;OAQG;IACH,UAAU,GAAG,CAAC,IAAY,EAAmB,EAAE;QAC7C,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,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EAAE;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAE5D,OAAO,2DAAG,QAAQ,GAAI,CAAC;IACzB,CAAC,CAAC;IAEF;;;;;;;;;OASG;IACH,SAAS,GAEJ,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAC3D,OAAO,2DAAG,QAAQ,GAAI,CAAC;IACzB,CAAC,CAAC;CACH;AAraD,+CAqaC","sourcesContent":["'use client';\nimport {\n // types\n Auth,\n Storage,\n txInit,\n type AuthState,\n type User,\n type ConnectionStatus,\n type TransactionChunk,\n type RoomSchemaShape,\n type InstaQLOptions,\n type InstantConfig,\n type PageInfoResponse,\n InstantCoreDatabase,\n init as core_init,\n InstaQLLifecycleState,\n InstaQLResponse,\n RoomsOf,\n InstantSchemaDef,\n IInstantDatabase,\n InstantError,\n ValidQuery,\n Streams,\n} from '@instantdb/core';\nimport {\n ReactNode,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useQueryInternal } from './useQuery.ts';\nimport {\n type InfiniteQueryResult,\n useInfiniteQuerySubscription,\n} from './useInfiniteQuerySubscription.ts';\nimport { InstantReactRoom, rooms } from './InstantReactRoom.ts';\n\nconst defaultAuthState = {\n isLoading: true,\n user: undefined,\n error: undefined,\n};\n\nexport default abstract class InstantReactAbstractDatabase<\n // need to pull this schema out to another generic for query params, not sure why\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n Config extends InstantConfig<Schema, boolean> = InstantConfig<\n Schema,\n UseDates\n >,\n Rooms extends RoomSchemaShape = RoomsOf<Schema>,\n> implements IInstantDatabase<Schema>\n{\n public tx = txInit<Schema>();\n\n public auth: Auth;\n public storage: Storage;\n public streams: Streams;\n public core: InstantCoreDatabase<Schema, UseDates>;\n\n /** @deprecated use `core` instead */\n public _core: InstantCoreDatabase<Schema, UseDates>;\n\n static Store?: any;\n static NetworkListener?: any;\n static EventSourceImpl?: any;\n\n constructor(\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n versions?: { [key: string]: string },\n ) {\n this.core = core_init<Schema, UseDates>(\n config,\n // @ts-expect-error because TS can't resolve subclass statics\n config.Store || this.constructor.Store,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.NetworkListener,\n versions,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.EventSourceImpl,\n );\n this._core = this.core;\n this.auth = this.core.auth;\n this.storage = this.core.storage;\n this.streams = this.core.streams;\n }\n\n /**\n * Returns a unique ID for a given `name`. It's stored in local storage,\n * so you will get the same ID across sessions.\n *\n * This is useful for generating IDs that could identify a local device or user.\n *\n * @example\n * const deviceId = await db.getLocalId('device');\n */\n getLocalId = (name: string): Promise<string> => {\n return this.core.getLocalId(name);\n };\n\n /**\n * A hook that returns a unique ID for a given `name`. localIds are\n * stored in local storage, so you will get the same ID across sessions.\n *\n * Initially returns `null`, and then loads the localId.\n *\n * @example\n * const deviceId = db.useLocalId('device');\n * if (!deviceId) return null; // loading\n * console.log('Device ID:', deviceId)\n */\n useLocalId = (name: string): string | null => {\n const [localId, setLocalId] = useState<string | null>(null);\n\n useEffect(() => {\n let mounted = true;\n const f = async () => {\n const id = await this.getLocalId(name);\n if (!mounted) return;\n setLocalId(id);\n };\n f();\n return;\n }, [name]);\n\n return localId;\n };\n\n /**\n * Obtain a handle to a room, which allows you to listen to topics and presence data\n *\n * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`\n * as the room type and id, respectively.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n */\n room<RoomType extends string & keyof Rooms>(\n type: RoomType = '_defaultRoomType' as RoomType,\n id: string = '_defaultRoomId',\n ) {\n return new InstantReactRoom<Schema, Rooms, RoomType>(this.core, type, id);\n }\n\n /**\n * Hooks for working with rooms\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n * // ...\n */\n rooms = rooms;\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact = (\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ) => {\n return this.core.transact(chunks);\n };\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * const { isLoading, error, data } = db.useQuery({ goals: {} });\n *\n * // goals where the title is \"Get Fit\"\n * const { isLoading, error, data } = db.useQuery({\n * goals: { $: { where: { title: 'Get Fit' } } },\n * });\n *\n * // all goals, _alongside_ their todos\n * const { isLoading, error, data } = db.useQuery({\n * goals: { todos: {} },\n * });\n *\n * // skip if `user` is not logged in\n * const { isLoading, error, data } = db.useQuery(\n * auth.user ? { goals: {} } : null,\n * );\n */\n useQuery = <Q extends ValidQuery<Q, Schema>>(\n query: null | Q,\n opts?: InstaQLOptions,\n ): InstaQLLifecycleState<Schema, Q, UseDates> => {\n return useQueryInternal<Q, Schema, UseDates>(this.core, query, opts).state;\n };\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * Check out the docs for an example `Login` component too!\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * function App() {\n * const { isLoading, user, error } = db.useAuth()\n * if (isLoading) {\n * return <div>Loading...</div>\n * }\n * if (error) {\n * return <div>Uh oh! {error.message}</div>\n * }\n * if (user) {\n * return <Main user={user} />\n * }\n * return <Login />\n * }\n *\n */\n useAuth = (): AuthState => {\n return this._useAuth();\n };\n\n protected _useAuth(): AuthState {\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<AuthState>(\n this.core._reactor._currentUserCached,\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeAuth((auth) => {\n resultCacheRef.current = { isLoading: false, ...auth };\n cb();\n });\n\n return unsubscribe;\n }, []);\n\n const state = useSyncExternalStore<AuthState>(\n subscribe,\n () => resultCacheRef.current,\n () => defaultAuthState,\n );\n return state;\n }\n\n /**\n * Subscribe to the currently logged in user.\n * If the user is not logged in, this hook with throw an Error.\n * You will want to protect any calls of this hook with a\n * <db.SignedIn> component, or your own logic based on db.useAuth()\n *\n * @see https://instantdb.com/docs/auth\n * @throws Error indicating user not signed in\n * @example\n * function UserDisplay() {\n * const user = db.useUser()\n * return <div>Logged in as: {user.email}</div>\n * }\n *\n * <db.SignedIn>\n * <UserDisplay />\n * </db.SignedIn>\n *\n */\n useUser = (): User => {\n const { user } = this.useAuth();\n if (!user) {\n throw new InstantError(\n 'useUser must be used within an auth-protected route',\n );\n }\n return user;\n };\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this.core.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. Use this for things like\n * showing connection state to users\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * function App() {\n * const status = db.useConnectionStatus()\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * return <div>Connection state: {connectionState}</div>\n * }\n */\n useConnectionStatus = (): ConnectionStatus => {\n const statusRef = useRef<ConnectionStatus>(\n this.core._reactor.status as ConnectionStatus,\n );\n\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {\n if (newStatus !== statusRef.current) {\n statusRef.current = newStatus;\n cb();\n }\n });\n\n return unsubscribe;\n }, []);\n\n const status = useSyncExternalStore<ConnectionStatus>(\n subscribe,\n () => statusRef.current,\n // For SSR, always return 'connecting' as the initial state\n () => 'connecting',\n );\n\n return status;\n };\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> => {\n return this.core.queryOnce(query, opts);\n };\n\n /**\n * Subscribe to a query and incrementally load more items\n *\n * Only one top level namespace in the query is allowed.\n *\n * Changing the query or options while the subscription is active will\n * reset the subscription and start over with new data.\n * @example\n * const {\n * data,\n * loadNextPage,\n * canLoadNextPage,\n * } = db.useInfiniteQuery({\n * posts: {\n * $: {\n * limit: 20, // Load 20 posts at a time\n * order: {\n * createdAt: 'desc',\n * },\n * },\n * },\n * });\n */\n useInfiniteQuery = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): InfiniteQueryResult<Schema, Q, UseDates> => {\n const result = useInfiniteQuerySubscription<Schema, Q, UseDates>({\n core: this.core,\n query: query,\n opts,\n });\n return result;\n };\n\n /**\n * Only render children if the user is signed in.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedIn>\n * <MyComponent />\n * </db.SignedIn>\n *\n */\n SignedIn: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || !auth.user) return null;\n\n return <>{children}</>;\n };\n\n /**\n * Only render children if the user is signed out.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedOut>\n * <MyComponent />\n * </db.SignedOut>\n *\n */\n SignedOut: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || auth.user) return null;\n return <>{children}</>;\n };\n}\n"]}
1
+ {"version":3,"file":"InstantReactAbstractDatabase.js","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;AACb,0CAwByB;AACzB,iCAOe;AACf,+CAAiD;AACjD,uFAG2C;AAC3C,+DAAgE;AAEhE,MAAM,gBAAgB,GAAG;IACvB,SAAS,EAAE,IAAI;IACf,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,SAAS;CACjB,CAAC;AAEF,MAAM,qBAAqB,GAAmB;IAC5C,SAAS,EAAE,IAAI;IACf,UAAU,EAAE,SAAS;CACtB,CAAC;AAEF,MAA8B,4BAA4B;IAWjD,EAAE,GAAG,IAAA,aAAM,GAAU,CAAC;IAEtB,IAAI,CAAO;IACX,OAAO,CAAU;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AC,CAAC;IAEF;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,gBAAgB,GAAG,CACjB,KAAQ,EACR,IAAqB,EACqB,EAAE;QAC5C,MAAM,MAAM,GAAG,IAAA,8DAA4B,EAAsB;YAC/D,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,KAAK,EAAE,KAAK;YACZ,IAAI;SACL,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF;;;;;;;;;OASG;IACH,QAAQ,GAEH,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAE5D,OAAO,2DAAG,QAAQ,GAAI,CAAC;IACzB,CAAC,CAAC;IAEF;;;;;;;;;OASG;IACH,SAAS,GAEJ,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAC3D,OAAO,2DAAG,QAAQ,GAAI,CAAC;IACzB,CAAC,CAAC;CACH;AAzcD,+CAycC","sourcesContent":["'use client';\nimport {\n // types\n Auth,\n Storage,\n txInit,\n type AuthState,\n type User,\n type ConnectionStatus,\n type AppStatusState,\n type TransactionChunk,\n type RoomSchemaShape,\n type InstaQLOptions,\n type InstantConfig,\n type PageInfoResponse,\n InstantCoreDatabase,\n init as core_init,\n InstaQLLifecycleState,\n InstaQLResponse,\n RoomsOf,\n InstantSchemaDef,\n IInstantDatabase,\n InstantError,\n ValidQuery,\n Streams,\n} from '@instantdb/core';\nimport {\n ReactNode,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useQueryInternal } from './useQuery.ts';\nimport {\n type InfiniteQueryResult,\n useInfiniteQuerySubscription,\n} from './useInfiniteQuerySubscription.ts';\nimport { InstantReactRoom, rooms } from './InstantReactRoom.ts';\n\nconst defaultAuthState = {\n isLoading: true,\n user: undefined,\n error: undefined,\n};\n\nconst defaultAppStatusState: AppStatusState = {\n isLoading: true,\n isReadOnly: undefined,\n};\n\nexport default abstract class InstantReactAbstractDatabase<\n // need to pull this schema out to another generic for query params, not sure why\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n Config extends InstantConfig<Schema, boolean> = InstantConfig<\n Schema,\n UseDates\n >,\n Rooms extends RoomSchemaShape = RoomsOf<Schema>,\n> implements IInstantDatabase<Schema>\n{\n public tx = txInit<Schema>();\n\n public auth: Auth;\n public storage: Storage;\n public streams: Streams;\n public core: InstantCoreDatabase<Schema, UseDates>;\n\n /** @deprecated use `core` instead */\n public _core: InstantCoreDatabase<Schema, UseDates>;\n\n static Store?: any;\n static NetworkListener?: any;\n static EventSourceImpl?: any;\n\n constructor(\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n versions?: { [key: string]: string },\n ) {\n this.core = core_init<Schema, UseDates>(\n config,\n // @ts-expect-error because TS can't resolve subclass statics\n config.Store || this.constructor.Store,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.NetworkListener,\n versions,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.EventSourceImpl,\n );\n this._core = this.core;\n this.auth = this.core.auth;\n this.storage = this.core.storage;\n this.streams = this.core.streams;\n }\n\n /**\n * Returns a unique ID for a given `name`. It's stored in local storage,\n * so you will get the same ID across sessions.\n *\n * This is useful for generating IDs that could identify a local device or user.\n *\n * @example\n * const deviceId = await db.getLocalId('device');\n */\n getLocalId = (name: string): Promise<string> => {\n return this.core.getLocalId(name);\n };\n\n /**\n * A hook that returns a unique ID for a given `name`. localIds are\n * stored in local storage, so you will get the same ID across sessions.\n *\n * Initially returns `null`, and then loads the localId.\n *\n * @example\n * const deviceId = db.useLocalId('device');\n * if (!deviceId) return null; // loading\n * console.log('Device ID:', deviceId)\n */\n useLocalId = (name: string): string | null => {\n const [localId, setLocalId] = useState<string | null>(null);\n\n useEffect(() => {\n let mounted = true;\n const f = async () => {\n const id = await this.getLocalId(name);\n if (!mounted) return;\n setLocalId(id);\n };\n f();\n return;\n }, [name]);\n\n return localId;\n };\n\n /**\n * Obtain a handle to a room, which allows you to listen to topics and presence data\n *\n * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`\n * as the room type and id, respectively.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n */\n room<RoomType extends string & keyof Rooms>(\n type: RoomType = '_defaultRoomType' as RoomType,\n id: string = '_defaultRoomId',\n ) {\n return new InstantReactRoom<Schema, Rooms, RoomType>(this.core, type, id);\n }\n\n /**\n * Hooks for working with rooms\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n * // ...\n */\n rooms = rooms;\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact = (\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ) => {\n return this.core.transact(chunks);\n };\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * const { isLoading, error, data } = db.useQuery({ goals: {} });\n *\n * // goals where the title is \"Get Fit\"\n * const { isLoading, error, data } = db.useQuery({\n * goals: { $: { where: { title: 'Get Fit' } } },\n * });\n *\n * // all goals, _alongside_ their todos\n * const { isLoading, error, data } = db.useQuery({\n * goals: { todos: {} },\n * });\n *\n * // skip if `user` is not logged in\n * const { isLoading, error, data } = db.useQuery(\n * auth.user ? { goals: {} } : null,\n * );\n */\n useQuery = <Q extends ValidQuery<Q, Schema>>(\n query: null | Q,\n opts?: InstaQLOptions,\n ): InstaQLLifecycleState<Schema, Q, UseDates> => {\n return useQueryInternal<Q, Schema, UseDates>(this.core, query, opts).state;\n };\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * Check out the docs for an example `Login` component too!\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * function App() {\n * const { isLoading, user, error } = db.useAuth()\n * if (isLoading) {\n * return <div>Loading...</div>\n * }\n * if (error) {\n * return <div>Uh oh! {error.message}</div>\n * }\n * if (user) {\n * return <Main user={user} />\n * }\n * return <Login />\n * }\n *\n */\n useAuth = (): AuthState => {\n return this._useAuth();\n };\n\n protected _useAuth(): AuthState {\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<AuthState>(\n this.core._reactor._currentUserCached,\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeAuth((auth) => {\n resultCacheRef.current = { isLoading: false, ...auth };\n cb();\n });\n\n return unsubscribe;\n }, []);\n\n const state = useSyncExternalStore<AuthState>(\n subscribe,\n () => resultCacheRef.current,\n () => defaultAuthState,\n );\n return state;\n }\n\n /**\n * Subscribe to the currently logged in user.\n * If the user is not logged in, this hook with throw an Error.\n * You will want to protect any calls of this hook with a\n * <db.SignedIn> component, or your own logic based on db.useAuth()\n *\n * @see https://instantdb.com/docs/auth\n * @throws Error indicating user not signed in\n * @example\n * function UserDisplay() {\n * const user = db.useUser()\n * return <div>Logged in as: {user.email}</div>\n * }\n *\n * <db.SignedIn>\n * <UserDisplay />\n * </db.SignedIn>\n *\n */\n useUser = (): User => {\n const { user } = this.useAuth();\n if (!user) {\n throw new InstantError(\n 'useUser must be used within an auth-protected route',\n );\n }\n return user;\n };\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this.core.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. Use this for things like\n * showing connection state to users\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * function App() {\n * const status = db.useConnectionStatus()\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * return <div>Connection state: {connectionState}</div>\n * }\n */\n useConnectionStatus = (): ConnectionStatus => {\n const statusRef = useRef<ConnectionStatus>(\n this.core._reactor.status as ConnectionStatus,\n );\n\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {\n if (newStatus !== statusRef.current) {\n statusRef.current = newStatus;\n cb();\n }\n });\n\n return unsubscribe;\n }, []);\n\n const status = useSyncExternalStore<ConnectionStatus>(\n subscribe,\n () => statusRef.current,\n // For SSR, always return 'connecting' as the initial state\n () => 'connecting',\n );\n\n return status;\n };\n\n /**\n * Observe the app's maintenance-mode state. While read-only, reads and\n * live queries keep working but writes are rejected.\n *\n * @example\n * function App() {\n * const { isLoading, isReadOnly } = db.useAppStatus()\n * if (isLoading) return null\n * if (isReadOnly) return <MaintenanceBanner />\n * // ...\n * }\n */\n useAppStatus = (): AppStatusState => {\n const stateRef = useRef<AppStatusState>(this.core._reactor._appStatusState);\n\n const subscribe = useCallback((cb: () => void) => {\n return this.core.subscribeAppStatus((state) => {\n if (\n state.isLoading !== stateRef.current.isLoading ||\n state.isReadOnly !== stateRef.current.isReadOnly\n ) {\n stateRef.current = state;\n cb();\n }\n });\n }, []);\n\n const state = useSyncExternalStore<AppStatusState>(\n subscribe,\n () => stateRef.current,\n () => defaultAppStatusState,\n );\n\n return state;\n };\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> => {\n return this.core.queryOnce(query, opts);\n };\n\n /**\n * Subscribe to a query and incrementally load more items\n *\n * Only one top level namespace in the query is allowed.\n *\n * Changing the query or options while the subscription is active will\n * reset the subscription and start over with new data.\n * @example\n * const {\n * data,\n * loadNextPage,\n * canLoadNextPage,\n * } = db.useInfiniteQuery({\n * posts: {\n * $: {\n * limit: 20, // Load 20 posts at a time\n * order: {\n * createdAt: 'desc',\n * },\n * },\n * },\n * });\n */\n useInfiniteQuery = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): InfiniteQueryResult<Schema, Q, UseDates> => {\n const result = useInfiniteQuerySubscription<Schema, Q, UseDates>({\n core: this.core,\n query: query,\n opts,\n });\n return result;\n };\n\n /**\n * Only render children if the user is signed in.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedIn>\n * <MyComponent />\n * </db.SignedIn>\n *\n */\n SignedIn: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || !auth.user) return null;\n\n return <>{children}</>;\n };\n\n /**\n * Only render children if the user is signed out.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedOut>\n * <MyComponent />\n * </db.SignedOut>\n *\n */\n SignedOut: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || auth.user) return null;\n return <>{children}</>;\n };\n}\n"]}
@@ -1,4 +1,4 @@
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, Streams } from '@instantdb/core';
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
2
  import { ReactNode } from 'react';
3
3
  import { type InfiniteQueryResult } from './useInfiniteQuerySubscription.ts';
4
4
  import { InstantReactRoom } from './InstantReactRoom.ts';
@@ -199,6 +199,19 @@ export default abstract class InstantReactAbstractDatabase<Schema extends Instan
199
199
  * }
200
200
  */
201
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;
202
215
  /**
203
216
  * Use this for one-off queries.
204
217
  * Returns local data if available, otherwise fetches from the server.
@@ -1 +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,KAAK,IAAI,EACT,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,mBAAmB,EAEnB,qBAAqB,EACrB,eAAe,EACf,OAAO,EACP,gBAAgB,EAChB,gBAAgB,EAEhB,UAAU,EACV,OAAO,EACR,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,SAAS,EAMV,MAAM,OAAO,CAAC;AAEf,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAS,MAAM,uBAAuB,CAAC;AAQhE,MAAM,CAAC,OAAO,CAAC,QAAQ,OAAO,4BAA4B,CAExD,MAAM,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAC9C,QAAQ,SAAS,OAAO,GAAG,KAAK,EAChC,MAAM,SAAS,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,aAAa,CAC3D,MAAM,EACN,QAAQ,CACT,EACD,KAAK,SAAS,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAC/C,YAAW,gBAAgB,CAAC,MAAM,CAAC;IAE5B,EAAE,4CAAoB;IAEtB,IAAI,EAAE,IAAI,CAAC;IACX,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAEnD,qCAAqC;IAC9B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,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"}
@@ -10,6 +10,10 @@ const defaultAuthState = {
10
10
  user: undefined,
11
11
  error: undefined,
12
12
  };
13
+ const defaultAppStatusState = {
14
+ isLoading: true,
15
+ isReadOnly: undefined,
16
+ };
13
17
  export default class InstantReactAbstractDatabase {
14
18
  tx = txInit();
15
19
  auth;
@@ -274,6 +278,32 @@ export default class InstantReactAbstractDatabase {
274
278
  () => 'connecting');
275
279
  return status;
276
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
+ };
277
307
  /**
278
308
  * Use this for one-off queries.
279
309
  * Returns local data if available, otherwise fetches from the server.
@@ -1 +1 @@
1
- {"version":3,"file":"InstantReactAbstractDatabase.js","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AACb,OAAO,EAIL,MAAM,EAUN,IAAI,IAAI,SAAS,EAMjB,YAAY,GAGb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,WAAW,EACX,SAAS,EACT,MAAM,EACN,QAAQ,EACR,oBAAoB,GACrB,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAEL,4BAA4B,GAC7B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAEhE,MAAM,gBAAgB,GAAG;IACvB,SAAS,EAAE,IAAI;IACf,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,SAAS;CACjB,CAAC;AAEF,MAAM,CAAC,OAAO,OAAgB,4BAA4B;IAWjD,EAAE,GAAG,MAAM,EAAU,CAAC;IAEtB,IAAI,CAAO;IACX,OAAO,CAAU;IACjB,OAAO,CAAU;IACjB,IAAI,CAAwC;IAEnD,qCAAqC;IAC9B,KAAK,CAAwC;IAEpD,MAAM,CAAC,KAAK,CAAO;IACnB,MAAM,CAAC,eAAe,CAAO;IAC7B,MAAM,CAAC,eAAe,CAAO;IAE7B,YACE,MAEC,EACD,QAAoC;QAEpC,IAAI,CAAC,IAAI,GAAG,SAAS,CACnB,MAAM;QACN,6DAA6D;QAC7D,MAAM,CAAC,KAAK,IA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AAQ,EACR,IAAqB,EAIpB,EAAE;QACH,OAAO,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC1C,CAAC,CAAC;IAEF;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,gBAAgB,GAAG,CACjB,KAAQ,EACR,IAAqB,EACqB,EAAE;QAC5C,MAAM,MAAM,GAAG,4BAA4B,CAAsB;YAC/D,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,KAAK,EAAE,KAAK;YACZ,IAAI;SACL,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF;;;;;;;;;OASG;IACH,QAAQ,GAEH,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAE5D,OAAO,4BAAG,QAAQ,GAAI,CAAC;IACzB,CAAC,CAAC;IAEF;;;;;;;;;OASG;IACH,SAAS,GAEJ,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAC3D,OAAO,4BAAG,QAAQ,GAAI,CAAC;IACzB,CAAC,CAAC;CACH","sourcesContent":["'use client';\nimport {\n // types\n Auth,\n Storage,\n txInit,\n type AuthState,\n type User,\n type ConnectionStatus,\n type TransactionChunk,\n type RoomSchemaShape,\n type InstaQLOptions,\n type InstantConfig,\n type PageInfoResponse,\n InstantCoreDatabase,\n init as core_init,\n InstaQLLifecycleState,\n InstaQLResponse,\n RoomsOf,\n InstantSchemaDef,\n IInstantDatabase,\n InstantError,\n ValidQuery,\n Streams,\n} from '@instantdb/core';\nimport {\n ReactNode,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useQueryInternal } from './useQuery.ts';\nimport {\n type InfiniteQueryResult,\n useInfiniteQuerySubscription,\n} from './useInfiniteQuerySubscription.ts';\nimport { InstantReactRoom, rooms } from './InstantReactRoom.ts';\n\nconst defaultAuthState = {\n isLoading: true,\n user: undefined,\n error: undefined,\n};\n\nexport default abstract class InstantReactAbstractDatabase<\n // need to pull this schema out to another generic for query params, not sure why\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n Config extends InstantConfig<Schema, boolean> = InstantConfig<\n Schema,\n UseDates\n >,\n Rooms extends RoomSchemaShape = RoomsOf<Schema>,\n> implements IInstantDatabase<Schema>\n{\n public tx = txInit<Schema>();\n\n public auth: Auth;\n public storage: Storage;\n public streams: Streams;\n public core: InstantCoreDatabase<Schema, UseDates>;\n\n /** @deprecated use `core` instead */\n public _core: InstantCoreDatabase<Schema, UseDates>;\n\n static Store?: any;\n static NetworkListener?: any;\n static EventSourceImpl?: any;\n\n constructor(\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n versions?: { [key: string]: string },\n ) {\n this.core = core_init<Schema, UseDates>(\n config,\n // @ts-expect-error because TS can't resolve subclass statics\n config.Store || this.constructor.Store,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.NetworkListener,\n versions,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.EventSourceImpl,\n );\n this._core = this.core;\n this.auth = this.core.auth;\n this.storage = this.core.storage;\n this.streams = this.core.streams;\n }\n\n /**\n * Returns a unique ID for a given `name`. It's stored in local storage,\n * so you will get the same ID across sessions.\n *\n * This is useful for generating IDs that could identify a local device or user.\n *\n * @example\n * const deviceId = await db.getLocalId('device');\n */\n getLocalId = (name: string): Promise<string> => {\n return this.core.getLocalId(name);\n };\n\n /**\n * A hook that returns a unique ID for a given `name`. localIds are\n * stored in local storage, so you will get the same ID across sessions.\n *\n * Initially returns `null`, and then loads the localId.\n *\n * @example\n * const deviceId = db.useLocalId('device');\n * if (!deviceId) return null; // loading\n * console.log('Device ID:', deviceId)\n */\n useLocalId = (name: string): string | null => {\n const [localId, setLocalId] = useState<string | null>(null);\n\n useEffect(() => {\n let mounted = true;\n const f = async () => {\n const id = await this.getLocalId(name);\n if (!mounted) return;\n setLocalId(id);\n };\n f();\n return;\n }, [name]);\n\n return localId;\n };\n\n /**\n * Obtain a handle to a room, which allows you to listen to topics and presence data\n *\n * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`\n * as the room type and id, respectively.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n */\n room<RoomType extends string & keyof Rooms>(\n type: RoomType = '_defaultRoomType' as RoomType,\n id: string = '_defaultRoomId',\n ) {\n return new InstantReactRoom<Schema, Rooms, RoomType>(this.core, type, id);\n }\n\n /**\n * Hooks for working with rooms\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n * // ...\n */\n rooms = rooms;\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact = (\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ) => {\n return this.core.transact(chunks);\n };\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * const { isLoading, error, data } = db.useQuery({ goals: {} });\n *\n * // goals where the title is \"Get Fit\"\n * const { isLoading, error, data } = db.useQuery({\n * goals: { $: { where: { title: 'Get Fit' } } },\n * });\n *\n * // all goals, _alongside_ their todos\n * const { isLoading, error, data } = db.useQuery({\n * goals: { todos: {} },\n * });\n *\n * // skip if `user` is not logged in\n * const { isLoading, error, data } = db.useQuery(\n * auth.user ? { goals: {} } : null,\n * );\n */\n useQuery = <Q extends ValidQuery<Q, Schema>>(\n query: null | Q,\n opts?: InstaQLOptions,\n ): InstaQLLifecycleState<Schema, Q, UseDates> => {\n return useQueryInternal<Q, Schema, UseDates>(this.core, query, opts).state;\n };\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * Check out the docs for an example `Login` component too!\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * function App() {\n * const { isLoading, user, error } = db.useAuth()\n * if (isLoading) {\n * return <div>Loading...</div>\n * }\n * if (error) {\n * return <div>Uh oh! {error.message}</div>\n * }\n * if (user) {\n * return <Main user={user} />\n * }\n * return <Login />\n * }\n *\n */\n useAuth = (): AuthState => {\n return this._useAuth();\n };\n\n protected _useAuth(): AuthState {\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<AuthState>(\n this.core._reactor._currentUserCached,\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeAuth((auth) => {\n resultCacheRef.current = { isLoading: false, ...auth };\n cb();\n });\n\n return unsubscribe;\n }, []);\n\n const state = useSyncExternalStore<AuthState>(\n subscribe,\n () => resultCacheRef.current,\n () => defaultAuthState,\n );\n return state;\n }\n\n /**\n * Subscribe to the currently logged in user.\n * If the user is not logged in, this hook with throw an Error.\n * You will want to protect any calls of this hook with a\n * <db.SignedIn> component, or your own logic based on db.useAuth()\n *\n * @see https://instantdb.com/docs/auth\n * @throws Error indicating user not signed in\n * @example\n * function UserDisplay() {\n * const user = db.useUser()\n * return <div>Logged in as: {user.email}</div>\n * }\n *\n * <db.SignedIn>\n * <UserDisplay />\n * </db.SignedIn>\n *\n */\n useUser = (): User => {\n const { user } = this.useAuth();\n if (!user) {\n throw new InstantError(\n 'useUser must be used within an auth-protected route',\n );\n }\n return user;\n };\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this.core.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. Use this for things like\n * showing connection state to users\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * function App() {\n * const status = db.useConnectionStatus()\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * return <div>Connection state: {connectionState}</div>\n * }\n */\n useConnectionStatus = (): ConnectionStatus => {\n const statusRef = useRef<ConnectionStatus>(\n this.core._reactor.status as ConnectionStatus,\n );\n\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {\n if (newStatus !== statusRef.current) {\n statusRef.current = newStatus;\n cb();\n }\n });\n\n return unsubscribe;\n }, []);\n\n const status = useSyncExternalStore<ConnectionStatus>(\n subscribe,\n () => statusRef.current,\n // For SSR, always return 'connecting' as the initial state\n () => 'connecting',\n );\n\n return status;\n };\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> => {\n return this.core.queryOnce(query, opts);\n };\n\n /**\n * Subscribe to a query and incrementally load more items\n *\n * Only one top level namespace in the query is allowed.\n *\n * Changing the query or options while the subscription is active will\n * reset the subscription and start over with new data.\n * @example\n * const {\n * data,\n * loadNextPage,\n * canLoadNextPage,\n * } = db.useInfiniteQuery({\n * posts: {\n * $: {\n * limit: 20, // Load 20 posts at a time\n * order: {\n * createdAt: 'desc',\n * },\n * },\n * },\n * });\n */\n useInfiniteQuery = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): InfiniteQueryResult<Schema, Q, UseDates> => {\n const result = useInfiniteQuerySubscription<Schema, Q, UseDates>({\n core: this.core,\n query: query,\n opts,\n });\n return result;\n };\n\n /**\n * Only render children if the user is signed in.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedIn>\n * <MyComponent />\n * </db.SignedIn>\n *\n */\n SignedIn: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || !auth.user) return null;\n\n return <>{children}</>;\n };\n\n /**\n * Only render children if the user is signed out.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedOut>\n * <MyComponent />\n * </db.SignedOut>\n *\n */\n SignedOut: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || auth.user) return null;\n return <>{children}</>;\n };\n}\n"]}
1
+ {"version":3,"file":"InstantReactAbstractDatabase.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;;;;;;;;OASG;IACH,SAAS,GAEJ,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QAC3D,OAAO,4BAAG,QAAQ,GAAI,CAAC;IACzB,CAAC,CAAC;CACH","sourcesContent":["'use client';\nimport {\n // types\n Auth,\n Storage,\n txInit,\n type AuthState,\n type User,\n type ConnectionStatus,\n type AppStatusState,\n type TransactionChunk,\n type RoomSchemaShape,\n type InstaQLOptions,\n type InstantConfig,\n type PageInfoResponse,\n InstantCoreDatabase,\n init as core_init,\n InstaQLLifecycleState,\n InstaQLResponse,\n RoomsOf,\n InstantSchemaDef,\n IInstantDatabase,\n InstantError,\n ValidQuery,\n Streams,\n} from '@instantdb/core';\nimport {\n ReactNode,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useQueryInternal } from './useQuery.ts';\nimport {\n type InfiniteQueryResult,\n useInfiniteQuerySubscription,\n} from './useInfiniteQuerySubscription.ts';\nimport { InstantReactRoom, rooms } from './InstantReactRoom.ts';\n\nconst defaultAuthState = {\n isLoading: true,\n user: undefined,\n error: undefined,\n};\n\nconst defaultAppStatusState: AppStatusState = {\n isLoading: true,\n isReadOnly: undefined,\n};\n\nexport default abstract class InstantReactAbstractDatabase<\n // need to pull this schema out to another generic for query params, not sure why\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n Config extends InstantConfig<Schema, boolean> = InstantConfig<\n Schema,\n UseDates\n >,\n Rooms extends RoomSchemaShape = RoomsOf<Schema>,\n> implements IInstantDatabase<Schema>\n{\n public tx = txInit<Schema>();\n\n public auth: Auth;\n public storage: Storage;\n public streams: Streams;\n public core: InstantCoreDatabase<Schema, UseDates>;\n\n /** @deprecated use `core` instead */\n public _core: InstantCoreDatabase<Schema, UseDates>;\n\n static Store?: any;\n static NetworkListener?: any;\n static EventSourceImpl?: any;\n\n constructor(\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n versions?: { [key: string]: string },\n ) {\n this.core = core_init<Schema, UseDates>(\n config,\n // @ts-expect-error because TS can't resolve subclass statics\n config.Store || this.constructor.Store,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.NetworkListener,\n versions,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.EventSourceImpl,\n );\n this._core = this.core;\n this.auth = this.core.auth;\n this.storage = this.core.storage;\n this.streams = this.core.streams;\n }\n\n /**\n * Returns a unique ID for a given `name`. It's stored in local storage,\n * so you will get the same ID across sessions.\n *\n * This is useful for generating IDs that could identify a local device or user.\n *\n * @example\n * const deviceId = await db.getLocalId('device');\n */\n getLocalId = (name: string): Promise<string> => {\n return this.core.getLocalId(name);\n };\n\n /**\n * A hook that returns a unique ID for a given `name`. localIds are\n * stored in local storage, so you will get the same ID across sessions.\n *\n * Initially returns `null`, and then loads the localId.\n *\n * @example\n * const deviceId = db.useLocalId('device');\n * if (!deviceId) return null; // loading\n * console.log('Device ID:', deviceId)\n */\n useLocalId = (name: string): string | null => {\n const [localId, setLocalId] = useState<string | null>(null);\n\n useEffect(() => {\n let mounted = true;\n const f = async () => {\n const id = await this.getLocalId(name);\n if (!mounted) return;\n setLocalId(id);\n };\n f();\n return;\n }, [name]);\n\n return localId;\n };\n\n /**\n * Obtain a handle to a room, which allows you to listen to topics and presence data\n *\n * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`\n * as the room type and id, respectively.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n */\n room<RoomType extends string & keyof Rooms>(\n type: RoomType = '_defaultRoomType' as RoomType,\n id: string = '_defaultRoomId',\n ) {\n return new InstantReactRoom<Schema, Rooms, RoomType>(this.core, type, id);\n }\n\n /**\n * Hooks for working with rooms\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n * // ...\n */\n rooms = rooms;\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact = (\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ) => {\n return this.core.transact(chunks);\n };\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * const { isLoading, error, data } = db.useQuery({ goals: {} });\n *\n * // goals where the title is \"Get Fit\"\n * const { isLoading, error, data } = db.useQuery({\n * goals: { $: { where: { title: 'Get Fit' } } },\n * });\n *\n * // all goals, _alongside_ their todos\n * const { isLoading, error, data } = db.useQuery({\n * goals: { todos: {} },\n * });\n *\n * // skip if `user` is not logged in\n * const { isLoading, error, data } = db.useQuery(\n * auth.user ? { goals: {} } : null,\n * );\n */\n useQuery = <Q extends ValidQuery<Q, Schema>>(\n query: null | Q,\n opts?: InstaQLOptions,\n ): InstaQLLifecycleState<Schema, Q, UseDates> => {\n return useQueryInternal<Q, Schema, UseDates>(this.core, query, opts).state;\n };\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * Check out the docs for an example `Login` component too!\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * function App() {\n * const { isLoading, user, error } = db.useAuth()\n * if (isLoading) {\n * return <div>Loading...</div>\n * }\n * if (error) {\n * return <div>Uh oh! {error.message}</div>\n * }\n * if (user) {\n * return <Main user={user} />\n * }\n * return <Login />\n * }\n *\n */\n useAuth = (): AuthState => {\n return this._useAuth();\n };\n\n protected _useAuth(): AuthState {\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<AuthState>(\n this.core._reactor._currentUserCached,\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeAuth((auth) => {\n resultCacheRef.current = { isLoading: false, ...auth };\n cb();\n });\n\n return unsubscribe;\n }, []);\n\n const state = useSyncExternalStore<AuthState>(\n subscribe,\n () => resultCacheRef.current,\n () => defaultAuthState,\n );\n return state;\n }\n\n /**\n * Subscribe to the currently logged in user.\n * If the user is not logged in, this hook with throw an Error.\n * You will want to protect any calls of this hook with a\n * <db.SignedIn> component, or your own logic based on db.useAuth()\n *\n * @see https://instantdb.com/docs/auth\n * @throws Error indicating user not signed in\n * @example\n * function UserDisplay() {\n * const user = db.useUser()\n * return <div>Logged in as: {user.email}</div>\n * }\n *\n * <db.SignedIn>\n * <UserDisplay />\n * </db.SignedIn>\n *\n */\n useUser = (): User => {\n const { user } = this.useAuth();\n if (!user) {\n throw new InstantError(\n 'useUser must be used within an auth-protected route',\n );\n }\n return user;\n };\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this.core.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. Use this for things like\n * showing connection state to users\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * function App() {\n * const status = db.useConnectionStatus()\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * return <div>Connection state: {connectionState}</div>\n * }\n */\n useConnectionStatus = (): ConnectionStatus => {\n const statusRef = useRef<ConnectionStatus>(\n this.core._reactor.status as ConnectionStatus,\n );\n\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {\n if (newStatus !== statusRef.current) {\n statusRef.current = newStatus;\n cb();\n }\n });\n\n return unsubscribe;\n }, []);\n\n const status = useSyncExternalStore<ConnectionStatus>(\n subscribe,\n () => statusRef.current,\n // For SSR, always return 'connecting' as the initial state\n () => 'connecting',\n );\n\n return status;\n };\n\n /**\n * Observe the app's maintenance-mode state. While read-only, reads and\n * live queries keep working but writes are rejected.\n *\n * @example\n * function App() {\n * const { isLoading, isReadOnly } = db.useAppStatus()\n * if (isLoading) return null\n * if (isReadOnly) return <MaintenanceBanner />\n * // ...\n * }\n */\n useAppStatus = (): AppStatusState => {\n const stateRef = useRef<AppStatusState>(this.core._reactor._appStatusState);\n\n const subscribe = useCallback((cb: () => void) => {\n return this.core.subscribeAppStatus((state) => {\n if (\n state.isLoading !== stateRef.current.isLoading ||\n state.isReadOnly !== stateRef.current.isReadOnly\n ) {\n stateRef.current = state;\n cb();\n }\n });\n }, []);\n\n const state = useSyncExternalStore<AppStatusState>(\n subscribe,\n () => stateRef.current,\n () => defaultAppStatusState,\n );\n\n return state;\n };\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> => {\n return this.core.queryOnce(query, opts);\n };\n\n /**\n * Subscribe to a query and incrementally load more items\n *\n * Only one top level namespace in the query is allowed.\n *\n * Changing the query or options while the subscription is active will\n * reset the subscription and start over with new data.\n * @example\n * const {\n * data,\n * loadNextPage,\n * canLoadNextPage,\n * } = db.useInfiniteQuery({\n * posts: {\n * $: {\n * limit: 20, // Load 20 posts at a time\n * order: {\n * createdAt: 'desc',\n * },\n * },\n * },\n * });\n */\n useInfiniteQuery = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): InfiniteQueryResult<Schema, Q, UseDates> => {\n const result = useInfiniteQuerySubscription<Schema, Q, UseDates>({\n core: this.core,\n query: query,\n opts,\n });\n return result;\n };\n\n /**\n * Only render children if the user is signed in.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedIn>\n * <MyComponent />\n * </db.SignedIn>\n *\n */\n SignedIn: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || !auth.user) return null;\n\n return <>{children}</>;\n };\n\n /**\n * Only render children if the user is signed out.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedOut>\n * <MyComponent />\n * </db.SignedOut>\n *\n */\n SignedOut: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || auth.user) return null;\n return <>{children}</>;\n };\n}\n"]}